如何使用Stax xml解析器有选择地提取存在于父元素下的特定子元素(重复项)?

时间:2018-11-14 20:37:00

标签: java xml xml-parsing sax stax

我有一个XML文件,正在使用Stax API读取。对于单个元素<Branch><Currency>来说,它工作正常。对于唯一的子元素<AccountId>,它也可以很好地工作。我的问题是,在父元素<advisory><Fixed><Threat>中,存在重复的子元素,即<name>。如何提取父元素<name>下的<Fixed>元素

<Branch>XXXXX</Branch>
<Currency>XXXXXXX</Currency>
<Account>
   <accountID>XXXXXXXX</accountID>
</Account>
<Advisory> 
   <name>XXXXXXXXXX</name>
   <testDescription>XXXXXXXXXXXX</testDescription>
</Advisory> 
<Fixed>
   <name>XXXXXXXXXX</name>
   <root>XXXXXXXXXX</root>
</Fixed>
<Threat> 
   <name>XXXXXXXXXXX</name>
   <reference>XXXXXXXXXXXXXXXX</reference> 
</Threat>

以下是我的Stax Parser代码:-

public static void parseXmlData(String xmlData) {
  String tagContent = null;
  XMLStreamReader reader = XMLInputFactory.newInstance()
      .createXMLStreamReader(new ByteArrayInputStream(xmlData.getBytes()));

  while (reader.hasNext()) {
    int event = reader.next();

    switch(event) {
      case XMLStreamConstants.START_ELEMENT:
          break;  
      case XMLStreamConstants.CHARACTERS:
          tagContent = reader.getText().trim();
          break;
      case XMLStreamConstants.END_ELEMENT:
          switch (reader.getLocalName()) {
          case "Branch":
              System.out.println(tagContent);
              break;
          case "Currency":
              System.out.println(tagContent);
              break;
          case "accountID":
              System.out.println(tagContent);
              break;
          case "name":
              System.out.println(tagContent);
              break;
          default:
              System.out.println("Discarded:",reader.getLocalName());
              break;
         }
         break;
    default:
         System.out.println("Discarded", event);
         break;
   }}}
  

请向我提供解决方案,如何使用Stax分析器从父元素<name>下的<Fixed>元素中有选择地提取数据

0 个答案:

没有答案