首页 \ 问答 \ XML文件没有使用jdom进行更新(XML file is not updating using the jdom)

XML文件没有使用jdom进行更新(XML file is not updating using the jdom)

以下是我的java代码,用于读取xml文件并更新其中的一些值。

 public static void writeLexicon(String word, String tag) {
    int newFreq=0;
    int tagAvailability = 0;
    int wordAvaialbility = 0;
    try {
        if (new File("./src/Lexicon.xml").exists()) {

            Document readDoc = getXMLFile();
            Element root = readDoc.getRootElement();
            for (Element curElem : root.getChildren("lexiconElement")) {
                if (word.equals(curElem.getChildText("word"))) {  // word avaialble

                    List<Element> subEle = curElem.getChildren();

                    for (int i = 1; i < subEle.size(); i++) {
                        if (tag.equals(subEle.get(i).getChildText("tag"))) {

                            int curFreq = Integer.parseInt(subEle.get(i).getChildTextTrim("frequancy"));
                            newFreq = curFreq + 1;
                            subEle.get(i).getChild("frequancy").setText(String.valueOf(newFreq));
                            tagAvailability = 1;
                            //break;
                        }
                    }
                    if (tagAvailability == 0) {
                        Element newTag = new Element("tag").setText(tag);

                        Element newFrequancy = new Element("frequancy").setText("1");
                        newTag.addContent(newFrequancy);
                        curElem.addContent(newTag);
                    }

                    wordAvaialbility = 1;
                }


            }
            if (wordAvaialbility == 0) {
                Element lexiconElement = new Element("lexiconElement");
                Element newWord = new Element("word").setText(word);

                Element newTag = new Element("tag").setText(tag);

                Element newFrequancy = new Element("frequancy").setText("1");
                newTag.addContent(newFrequancy);
                lexiconElement.addContent(newWord);
                lexiconElement.addContent(newTag);

                root.addContent(lexiconElement);
                XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
                xmlOutput.output(readDoc, new FileOutputStream(new File("./src/Lexicon.xml")));


            }

        } else {

            Document doc = new Document(); // create  a JDOM document
            String freq = "1";
            Element theRoot = new Element("Lexicon"); // Creates a element named Lexicon and makes it the root
            doc.setRootElement(theRoot);

            Element lexiconElement = new Element("lexiconElement");
            Element Word = new Element("word");
            Element Tag = new Element("tag");
            Element frequency = new Element("frequency");

            Word.addContent(new Text(word));
            Tag.addContent(new Text(tag));
            frequency.addContent(new Text(freq));

            Tag.addContent(frequency);
            lexiconElement.addContent(Word);
            lexiconElement.addContent(Tag);

            theRoot.addContent(lexiconElement);
            XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
            xmlOutput.output(doc, new FileOutputStream(new File("./src/Lexicon.xml")));



        }


    } catch (Exception e) {
        System.out.println(e);
    }
}

我需要获取frequancy标记中的值并将值递增1并添加到相同的xml文件中。 但它没有使用上面的代码。

以下是我的xml文件中的几个元素。

  <lexiconElement>
    <word>හයිටිය</word>
    <tag>
      NNPI
      <frequency>1</frequency>
    </tag>
  </lexiconElement>
  <lexiconElement>
    <word>-2</word>
    <tag>
      QFNUM
      <frequancy>1</frequancy>
    </tag>
  </lexiconElement>
  <lexiconElement>
    <word>තමා</word>
    <tag>
      PRP
      <frequancy>1</frequancy>
    </tag>
  </lexiconElement>

following is my java code for reading a xml file and updating some values in it.

 public static void writeLexicon(String word, String tag) {
    int newFreq=0;
    int tagAvailability = 0;
    int wordAvaialbility = 0;
    try {
        if (new File("./src/Lexicon.xml").exists()) {

            Document readDoc = getXMLFile();
            Element root = readDoc.getRootElement();
            for (Element curElem : root.getChildren("lexiconElement")) {
                if (word.equals(curElem.getChildText("word"))) {  // word avaialble

                    List<Element> subEle = curElem.getChildren();

                    for (int i = 1; i < subEle.size(); i++) {
                        if (tag.equals(subEle.get(i).getChildText("tag"))) {

                            int curFreq = Integer.parseInt(subEle.get(i).getChildTextTrim("frequancy"));
                            newFreq = curFreq + 1;
                            subEle.get(i).getChild("frequancy").setText(String.valueOf(newFreq));
                            tagAvailability = 1;
                            //break;
                        }
                    }
                    if (tagAvailability == 0) {
                        Element newTag = new Element("tag").setText(tag);

                        Element newFrequancy = new Element("frequancy").setText("1");
                        newTag.addContent(newFrequancy);
                        curElem.addContent(newTag);
                    }

                    wordAvaialbility = 1;
                }


            }
            if (wordAvaialbility == 0) {
                Element lexiconElement = new Element("lexiconElement");
                Element newWord = new Element("word").setText(word);

                Element newTag = new Element("tag").setText(tag);

                Element newFrequancy = new Element("frequancy").setText("1");
                newTag.addContent(newFrequancy);
                lexiconElement.addContent(newWord);
                lexiconElement.addContent(newTag);

                root.addContent(lexiconElement);
                XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
                xmlOutput.output(readDoc, new FileOutputStream(new File("./src/Lexicon.xml")));


            }

        } else {

            Document doc = new Document(); // create  a JDOM document
            String freq = "1";
            Element theRoot = new Element("Lexicon"); // Creates a element named Lexicon and makes it the root
            doc.setRootElement(theRoot);

            Element lexiconElement = new Element("lexiconElement");
            Element Word = new Element("word");
            Element Tag = new Element("tag");
            Element frequency = new Element("frequency");

            Word.addContent(new Text(word));
            Tag.addContent(new Text(tag));
            frequency.addContent(new Text(freq));

            Tag.addContent(frequency);
            lexiconElement.addContent(Word);
            lexiconElement.addContent(Tag);

            theRoot.addContent(lexiconElement);
            XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
            xmlOutput.output(doc, new FileOutputStream(new File("./src/Lexicon.xml")));



        }


    } catch (Exception e) {
        System.out.println(e);
    }
}

i need to get the value in frequancy tag and increment the value by one and add to same xml file. but it didnt work with the above code.

following are few elements avaialble in my xml file.

  <lexiconElement>
    <word>හයිටිය</word>
    <tag>
      NNPI
      <frequency>1</frequency>
    </tag>
  </lexiconElement>
  <lexiconElement>
    <word>-2</word>
    <tag>
      QFNUM
      <frequancy>1</frequancy>
    </tag>
  </lexiconElement>
  <lexiconElement>
    <word>තමා</word>
    <tag>
      PRP
      <frequancy>1</frequancy>
    </tag>
  </lexiconElement>

原文:https://stackoverflow.com/questions/26108513
更新时间:2024-03-27 12:03

最满意答案

这里有很多方法,但是如果不了解你打算如何使用istream ,就很难给出好的建议。

关于这段代码的一件事是你绝对肯定地知道在istream的末尾会有一个换行符。 没有可以采用的代码路径不会导致(除了I / O错误,您将提前捕获)。

因此,编写希望\n存在并忽略它的代码非常简单。

显然,如果可能,您希望避免使用缓冲区副本。

但是,如果要将整个streambuf复制到字符串中,可以尝试这样做:

auto buf = buffer.data(); /* where buffer is your asio::streambuf */
auto s = std::string(boost::asio::buffer_cast<const char*>(buf), 
                     boost::asio::buffer_size(buf) - 1); /* remove the newline */

当然,如果你想要解析istream中的字符串,数字等,那么最后有一个换行的事实并不重要 - 它只是空格,默认情况下会被忽略。

这个迷你程序演示了这个:

#include <boost/asio.hpp>
#include <sstream>
#include <iomanip>
#include <iostream>


int main()
{
    std::ostringstream oss;

    oss << 10 << std::quoted("Hello\" World") << '\n';
    auto payload = oss.str();

    boost::asio::streambuf sb;
    std::ostream otmp(&sb);
    otmp.write(payload.data(), payload.size());

    // streambuf now contains string with newline

    std::string s;
    int i;
    std::istream itmp(&sb);
    itmp >> i >> std::quoted(s);

    std::cout << i << std::endl;   // expect 10
    std::cout << s << std::endl;   // expect Hello" World
}

There are a number of approaches here, but it's difficult to give good advice without knowing something about how you intend to use the istream.

One thing about this code is that you know with absolute certainty that there will be a newline at the end of the istream. There is no code path that can be taken that will not result in that (other than an I/O error, which you will catch early).

As a result it's straightforward to write code that expects the \n to be there and ignore it.

Obviously you want to avoid buffer copies if possible.

However, if you want to copy the entire streambuf into a string, you might try this:

auto buf = buffer.data(); /* where buffer is your asio::streambuf */
auto s = std::string(boost::asio::buffer_cast<const char*>(buf), 
                     boost::asio::buffer_size(buf) - 1); /* remove the newline */

Of course if you're looking to parse strings, numbers etc out of the istream then the fact that there is a newline on the end won't matter - it's just whitespace which is ignored by default.

This mini program demonstrates this:

#include <boost/asio.hpp>
#include <sstream>
#include <iomanip>
#include <iostream>


int main()
{
    std::ostringstream oss;

    oss << 10 << std::quoted("Hello\" World") << '\n';
    auto payload = oss.str();

    boost::asio::streambuf sb;
    std::ostream otmp(&sb);
    otmp.write(payload.data(), payload.size());

    // streambuf now contains string with newline

    std::string s;
    int i;
    std::istream itmp(&sb);
    itmp >> i >> std::quoted(s);

    std::cout << i << std::endl;   // expect 10
    std::cout << s << std::endl;   // expect Hello" World
}

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。