简体   繁体   English

如何使用JDOM以相同的名称编写和获取具有相同名称的所有xml元素

[英]how to write and get all the xml elements in same level with same name using JDOM

my xml file is as follows 我的xml文件如下

<lexicon>
  <lexiconElement>
    <word>xxxx</word>
    <tag>NN
      <frequancy>3</frequancy>
    </tag>
    <tag>VB
      <frequancy>2</frequancy>
    </tag>
  </lexiconElement>
</lexicon>

i need to know how to append many elements to same level in the same xml file when updating using JDOM and how to read those elements with the same name in same level using JDOM??? 我需要知道如何在使用JDOM更新时将多个元素添加到同一xml文件中的同一级别,以及如何使用JDOM在相同级别读取具有相同名称的那些元素?

I hope this is what you are looking for. 我希望这是您要寻找的。

try {

            SAXBuilder builder = new SAXBuilder();
            File xmlFile = new File("D:\\your_file.xml");

            Document doc = (Document) builder.build(xmlFile);
            Element rootNode = doc.getRootElement();

            Element lexiconElement = rootNode.getChild("lexiconElement");

            // 1. add new <tag> elements to xml
            Element newTag = new Element("your_new_tag").setText("your_new_tag_value");
            lexiconElement.addContent(newTag);

            // 2. Update the text between <frequancy> in perticular tag
            //lexiconElement.getChild("tag").getChild("frequancy").setText("9");

            // 2. Update the text between <frequancy> in all tag
            List<Element> list = lexiconElement.getChildren("tag");
            for(Element elm : list){
                elm.getChild("frequancy").setText("324");
            }

            // 3. Update the text between <word>
            lexiconElement.getChild("word").setText("yyyy");

            XMLOutputter xmlOutput = new XMLOutputter();

            xmlOutput.output(doc, new FileWriter("D:\\your_file.xml"));

            System.out.println("*********Done************");
        } catch (IOException io) {
            io.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM