简体   繁体   English

Java - 解析嵌套的xml文件并写入该文件

[英]Java - parse nested xml file and write to the file

I have a .xml file like below: 我有一个.xml文件,如下所示:

    <?xml version="1.0"?>
    <Event>
    <Issue>ggg</Issue>
    <City>Athen</City>   
      <Group>
      <AlternateIdentification>
        <AlternateID>DG800</AlternateID>
        <AlternateIDType>GoA</AlternateIDType>
      </AlternateIdentification>
      <AlternateIdentification>
        <AlternateID>SS500</AlternateID>
        <AlternateIDType>SDD</AlternateIDType>
      </AlternateIdentification>
      <AlternateIdentification>
        <AlternateID>TY158</AlternateID>
        <AlternateIDType>YTU</AlternateIDType>
      </AlternateIdentification>
      </Group>
    </Event>

And I would like to parse .xml file and write the output to the flat .txt file with lines like this: 我想解析.xml文件并将输出写入flat .txt文件,其行如下所示:

ggg Athen DG800
ggg Athen SS500
ggg Athen TY158

Can you help me and tell me how to do this with javax DOM parser? 你能帮助我并告诉我如何使用javax DOM解析器吗? I have no idea how to start :( This common part confuses me the most because I need to iterate this file in this case 3 times to get 3x " ggg Athen " and then additional tag AlternateID ? 我不知道如何开始:(这个常见的部分让我最困惑,因为我需要在这种情况下迭代这个文件3次以获得3x“ ggg Athen ”然后额外标记AlternateID

Java - parse nested xml file and write to the file Java - 解析嵌套的xml文件并写入该文件

A simple way : 一个简单的方法:

  1. Read line by line with BufferedReader.readLine() until finding the start of the nested xml part. 使用BufferedReader.readLine()逐行读取,直到找到嵌套xml部件的开头。
    For example : <?xml version="1.0"?> 例如: <?xml version="1.0"?>

  2. When you identified this line, add each read line in a StringBuilder instance until you encounter the end of the xml part that you want to analyse. 标识此行时,在StringBuilder实例中添加每个读取行,直到遇到要分析的xml部分的结尾。 For example the end tag of the root element of it. 例如,它的根元素的结束标记。
    Here : </Event> 这里: </Event>

  3. Create a org.w3c.dom.Document from the String contained in the StringBuilder : StringBuilder包含的String创建org.w3c.dom.Document

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader( stringBuilder.toString())));

  4. Use your preferred way to find data in the document : dom, jdom, xpath, etc... 使用您首选的方法在文档中查找数据:dom,jdom,xpath等...

You definitely need to look at Sax XML Parser. 你肯定需要看看Sax XML Parser。 Tutorial for that can be found here 可以在此处找到该教程

Good luck 祝好运

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

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