如何解析非常规XML文件

时间:2014-09-09 13:45:17

标签: java xml xml-parsing

我需要采用我认为的“非常规”XML文件,并将其转换为我认为“常规”的文件。以下XML示例已被“清除”专有名称/值。

以下是“非常规”XML文件的样子:

    <?xml version="1.0" encoding="UTF-8"?>
    <dataView name="document/aDocument" xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <dataItems>
        <dataItem name="item1" location="item1" dataItemType="Long">
            <value xsi:type="xs:string">1</value>
        </dataItem>
        <dataItem name="item2" location="item.seconditem(some item).ref" dataItemType="String">
            <value xsi:type="xs:string">ABC2DEF3</value>
        </dataItem>
    </dataItems>
    <dataRepeaters>
        <dataRepeater name="SomeLevel1" runtimeInfomration="SomeLevel11984371030">
            <dataGroups>
                <dataGroup name="SomeLevel2" location="SomeLevel:(a level).thelevel" keyValue="SomeLevel119843710300" runtimeInformation="19843710300">
                    <dataItems>
                        <dataItem name="someItem1" location="someLevel.aLevel(another item)" dataItemType="String">
                            <value xsi:type="xs:string">12345</value>
                        </dataItem>
                        <dataItem name="someItem2" location="someLevel.aLevel(another item2)" dataItemType="Integer"/>
                        <dataItem name="someItem3" location="someLevel.aLevel(another item3)" dataItemType="ObjectReference">
                            <value xsi:type="xs:string">11:20012:3536</value>
                        </dataItem>
                        <dataItem name="someItem4" location="someLevel.aLevel(another item4)" dataItemType="String"/>
                        <dataItem name="someItem5" location="someLevel.aLevel(another item5)" dataItemType="String">
                            <value xsi:type="xs:string">someItem5 Data</value>
                        </dataItem>
                        <dataItem name="someItem6" location="someLevel.aLevel(another item6)" dataItemType="CurrencyAmount">
                            <value xsi:type="xs:string">123456:USD</value>
                        </dataItem>
                    </dataItems>
                </dataGroup>
                <dataGroup name="SomeLevel3" keyValue="SomeLevel31984371030" runtimeInformation="1984371030">
                    <dataRepeaters>
                        <dataRepeater name="SomeLevel4" runtimeInfomration="SomeLevel4">
                            <dataGroups>
                                <dataGroup name="SomeLevel5" location="anotherLevel.level5(SomeLevel5):someLevel5" keyValue="SomeLevel51984371030-11521863690" runtimeInformation="1984371030-11521863690">
                                    <dataItems>
                                        <dataItem name="someItem6" location="someLevel.aLevel(another item6)" dataItemType="BigDecimal">
                                            <value xsi:type="xs:string">303.149</value>
                                        </dataItem>
                                        <dataItem name="someItem7" location="someLevel.aLevel(another item7)" dataItemType="CurrencyAmount">
                                            <value xsi:type="xs:string">117:USD</value>
                                        </dataItem>
                                        <dataItem name="someItem8" location="someLevel.aLevel(another item8)" dataItemType="String">
                                            <value xsi:type="xs:string">117.000000:USD</value>
                                        </dataItem>
                                        <dataItem name="someItem9" location="someLevel.aLevel(another item9)" dataItemType="CurrencyAmount">
                                            <value xsi:type="xs:string">117:USD</value>
                                        </dataItem>
                                    </dataItems>
                                    <dataRepeaters>
                                        <dataRepeater name="SomeLevel6" runtimeInfomration="someLevel6">
                                            <dataGroups/>
                                            </dataRepeater>
                                    </dataRepeaters>
                                </dataGroup>
                                <dataGroup name="SomeLevel7" location="anotherLevel.level5(SomeLevel7):someLevel7" keyValue="SomeLevel71984371030-11521863690" runtimeInformation="1984371030-11521863690">
                                    <dataItems>
                                        <dataItem name="someItem10" location="someLevel.aLevel(another item10)" dataItemType="BigDecimal">
                                            <value xsi:type="xs:string">292.741</value>
                                        </dataItem>
                                        <dataItem name="someItem11" location="someLevel.aLevel(another item11)" dataItemType="CurrencyAmount">
                                            <value xsi:type="xs:string">165:USD</value>
                                        </dataItem>
                                        <dataItem name="someItem12" location="someLevel.aLevel(another item12)" dataItemType="String">
                                            <value xsi:type="xs:string">165.000000:USD</value>
                                        </dataItem>
                                        <dataItem name="someItem13" location="someLevel.aLevel(another item13)" dataItemType="CurrencyAmount">
                                            <value xsi:type="xs:string">165:USD</value>
                                        </dataItem>
                                    </dataItems>
                                    <dataRepeaters/>
                                </dataGroup>
                                <dataGroup name="SomeLevel8" location="anotherLevel.level5(SomeLevel8):someLevel8" keyValue="SomeLevel81984371030-11521863690" runtimeInformation="1984371030-11521863690">
                                    <dataItems>
                                        <dataItem name="someItem14" location="someLevel.aLevel(another item14)" dataItemType="BigDecimal">
                                            <value xsi:type="xs:string">369.075</value>
                                        </dataItem>
                                        <dataItem name="someItem15" location="someLevel.aLevel(another item15)" dataItemType="CurrencyAmount">
                                            <value xsi:type="xs:string">598:USD</value>
                                        </dataItem>
                                        <dataItem name="someItem16" location="someLevel.aLevel(another item16)" dataItemType="String">
                                            <value xsi:type="xs:string">598.000000:USD</value>
                                        </dataItem>
                                    </dataItems>
                                    <dataRepeaters>
                                        <dataRepeater name="SomeLevel9" runtimeInfomration="someLevel9">
                                            <dataGroups>
                                                <dataGroup name="SomeLevel10" location="ownedAuto.AgreementActual(Liability).ConstantRole(Policy Form):policyForm" keyValue="aomeLevel101984371030-11521863690-115218636900" runtimeInformation="1984371030-11521863690-115218636900">
                                                    <dataItems>
                                                        <dataItem name="someItem17" location="someLevel.aLevel(another item17)" dataItemType="String">
                                                            <value xsi:type="xs:string">Some Data | ABC 123</value>
                                                        </dataItem>
                                                        <dataItem name="someItem18" location="someLevel.aLevel(another item18)" dataItemType="Integer">
                                                            <value xsi:type="xs:string">2</value>
                                                        </dataItem>
                                                    </dataItems>
                                                </dataGroup>
                                            </dataGroups>
                                        </dataRepeater>
                                        <dataRepeater name="SomeLevel10" runtimeInfomration="someLevel11">
                                            <dataGroups/>
                                        </dataRepeater>
                                    </dataRepeaters>
                                </dataGroup>
                            </dataGroups>
                        </dataRepeater>
                    </dataRepeaters>
                </dataGroup>
            </dataGroups>
        </dataRepeater>
    </dataRepeaters>
</dataView>

我想把它转换成这样的东西:

    <?xml version="1.0" encoding="UTF-8"?>
<dataView name="document/aDocument" xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <item1>1</item1>
  <item2>ABC2DEF3</item2>
  <SomeLevel1>
    <SomeLevel2>
      <someItem1>12345f</someItem1>
      <someItem2></someItem2>     
      <someItem3>11:20012:3536</someItem3>
      <someItem4>12345f</someItem4>
      <someItem5>someItem5 Data</someItem5>
      <someItem6>123456:USD</someItem6>
    </SomeLevel2>
    <SomeLevel3>
      <SomeLevel4>
        <SomeLevel5>
          <someItem7>303.149</someItem7>
          <someItem8>117:USD</someItem8>
          <someItem9>117.000000:USD</someItem9>
          <someItem10>117:USD</someItem10>
          <SomeLevel6></SomeLevel6>
        </SomeLevel5>
        <SomeLevel7>
          <someItem11>292.741</someItem11>
          <someItem12>165:USD</someItem12>
          <someItem13>165.000000:USD</someItem13>
          <someItem14>165:USD</someItem14>
        </SomeLevel7>
        <SomeLevel8>
          <someItem15>369.075</someItem15>
          <someItem16>598:USD</someItem16>
          <someItem17>598.000000:USD</someItem17>
          <SomeLevel9>
            <SomeLevel10>
              <someItem18>Some Data | ABC 123</someItem18>
              <someItem19>2</someItem19>
            </SomeLevel10>
          </SomeLevel9>
          <SomeLevel11></SomeLevel11>
        </SomeLevel8>
      </SomeLevel4>
    </SomeLevel3>
  </SomeLevel1>
</dataView>

所以基本上我正在尝试使用“name”属性并将其作为XML节点/标记以及<value>节点/标记之间的值,并将其用作XML节点/标记的“值”

我尝试了几种不同的解析/编写“例程”,下面两个是让我最接近的两个。所以我将其他人排除在外,因为他们只是“吵闹”。

这是我到目前为止所尝试的内容:

private Document xmlDocument;

public void convertXML() {
      xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("DSExample.xml")));

      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      Node dsNode = xmlDocument.getDocumentElement();

      xmlDocument = docBuilder.newDocument();

      // Attempt 1:   
      doSomethingDS(dsNode); // This will convert the XML but with NO nesting - creates example output 1
      // Attempt 2:
      traverseDS(dsNode); // This will create an XML with ONLY the root dataItems - Don't know why - creates example output 2
}

public void doSomethingDS(Node node) {  
    System.out.println(node.getNodeName());
    Element xmlElement = null;

    // This will be the "root" element/node "dataView":
    if(node.getNodeName() != null && node.getNodeName().equalsIgnoreCase("dataView")) {

      // Debugging: Print the node
      printNode(node);

      String nodeName = node.getNodeName().trim();
      rootElement = xmlDocument.createElement(nodeName);
      mPreviousElement = rootElement;

      addAllAttributesToRootElement((Element) node, rootElement);

      xmlDocument.appendChild(rootElement);
    }
    else {

        // Debugging: Print the node
        printNode(node);

        // If has "name" property - create element/node
        if(node.getAttributes() != null && node.getAttributes().getNamedItem("name") != null) {
          xmlElement = createElement(xmlDocument, node);

          if(xmlElement !=null && xmlDocument.getFirstChild() != null) {
            xmlDocument.getFirstChild().appendChild(xmlElement);  
          }
        }

    }    

    NodeList nodeList = node.getChildNodes();
    for(int i = 0; i < nodeList.getLength(); i++) {
      Node currentNode = nodeList.item(i);
      if(currentNode.getNodeType() == Node.ELEMENT_NODE) {
        // recursively call this method for all the children which are of type Element
        doSomethingDS(currentNode);
      }
    }
} // End of doSomethingDS() 


public void traverseDS(Node parentNode) {
    // This will create an XML with ONLY the root dataItems - Don't know why.

    Element xmlElement = null;

    //****************************************************************
    // This will be the "root" element/node "dataView":
    if(parentNode.getNodeName() != null && parentNode.getNodeName().equalsIgnoreCase("dataView")) {

      // Debugging: Print the node
      printNode(parentNode);

      String nodeName = parentNode.getNodeName().trim();
      rootElement = xmlDocument.createElement(nodeName);
      mPreviousElement = rootElement;

      if(!isRootNodeSet) {        
        mRootNode = parentNode;
        isRootNodeSet = true;
      }

      addAllAttributesToRootElement((Element) parentNode, rootElement);

      xmlDocument.appendChild(rootElement);

      // traverse children
      Node theNode = parentNode.getFirstChild();
      if(theNode != null) {
        theNode = theNode.getNextSibling();
      }
      else if (isRootNodeSet) {
        theNode = mRootNode.getNextSibling();
      }

      traverseDS(theNode);
    }
    else {

      // traverse all nodes that belong to the parent
      for(Node theNode = parentNode.getFirstChild(); theNode != null; theNode = theNode.getNextSibling()) {

        // Debugging: Print the node
        printNode(theNode);

        // If has "name" property - create element/node
        if(theNode.getAttributes() != null && theNode.getAttributes().getNamedItem("name") != null) {
          // Create new Element/Node
          xmlElement = createElement(xmlDocument, theNode);
          if(xmlElement !=null && xmlDocument.getFirstChild() != null) {
            xmlDocument.getFirstChild().appendChild(xmlElement);  
          }
          else {
            System.out.println(" not a node we wanted?");
          }
        }

        // traverse children     
        traverseDS(theNode);
      }
    }
} // End of traverseDS()
private Element createElement(Document aDoc, Node aNode) {
    Element xmlElement = null;
    String elementName = "";

    NamedNodeMap dataNodeMap = aNode.getAttributes();
    if(dataNodeMap != null && dataNodeMap.getNamedItem("name") != null) {

      elementName = dataNodeMap.getNamedItem("name").getTextContent();
      xmlElement = aDoc.createElement(elementName);

      // if node = "dataItem" - walk node to get <value> node
      // Note: some "dataItem" nodes also have a <previousValue> node - what to do with these????
      if(aNode.getNodeName() != null && aNode.getNodeName().equalsIgnoreCase("dataItem")) {
        // Walk Node to get <value> node
        NodeList childNodes = aNode.getChildNodes();
        int childNodesLength = childNodes.getLength();
        for(int x = 0; x < childNodesLength; x++) {
          Node childNode = childNodes.item(x);
          if(childNode.getNodeName() != null && childNode.getNodeName().equalsIgnoreCase("value")) {
            xmlElement.setTextContent(childNode.getTextContent());
            break;
          }
        }
      }
    }
    return xmlElement;
} // End of createElement()

示例输出1(由doSomethingDS()创建):

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<dataView xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="document/aDocument">
    <item1>1</item1>
    <item2>ABC2DEF3</item2>
    <SomeLevel1/>
    <SomeLevel2/>
    <someItem1>12345</someItem1>
    <someItem2/>
    <someItem3>11:20012:3536</someItem3>
    <someItem4/>
    <someItem5>someItem5 Data</someItem5>
    <someItem6>123456:USD</someItem6>
    <SomeLevel3/>
    <SomeLevel4/>
    <SomeLevel5/>
    <someItem6>303.149</someItem6>
    <someItem7>117:USD</someItem7>
    <someItem8>117.000000:USD</someItem8>
    <someItem9>117:USD</someItem9>
    <SomeLevel6/>
    <SomeLevel7/>
    <someItem10>292.741</someItem10>
    <someItem11>165:USD</someItem11>
    <someItem12>165.000000:USD</someItem12>
    <someItem13>165:USD</someItem13>
    <SomeLevel8/>
    <someItem14>369.075</someItem14>
    <someItem15>598:USD</someItem15>
    <someItem16>598.000000:USD</someItem16>
    <SomeLevel9/>
    <SomeLevel10/>
    <someItem17>Some Data | ABC 123</someItem17>
    <someItem18>2</someItem18>
    <SomeLevel11/>
</dataView>

示例输出2(由traverseDS()创建):

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<dataView xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="document/aDocument">
    <item1>1</item1>
    <item2>ABC2DEF3</item2>
</dataView>

现在,这就是抓住......我得到的是动态我可以一次获得一辆Mac卡车,一辆丰田汽车或者两者的混合物。我得到的XML的大小可能很小或很大。所以很难只使用XPath或直接追踪特定元素,因为我不知道我会得到什么。这就是为什么我基本上每次都在走DOM /遍历一个节点以提取出可用的东西。

所以我的问题是: 在解析/编写XML文件时,我做错了什么,以使它看起来不像我想让它看起来像什么?

2 个答案:

答案 0 :(得分:5)

使用XSLT(几乎)很简单:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:ds="http://component.mycompany.com/entity/ds" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://component.mycompany.com/entity/ds" 
>
  <xsl:output indent="yes" />
  <xsl:strip-space elements="*" />

  <xsl:template match="ds:dataView" priority="1">
    <xsl:copy>
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="ds:*[@name]">
    <xsl:element name="{@name}">
      <xsl:apply-templates />
    </xsl:element>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="normalize-space()" />
  </xsl:template>

</xsl:stylesheet>

应用你的输入,给你:

<dataView xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <item1>1</item1>
  <item2>ABC2DEF3</item2>
  <SomeLevel1>
    <SomeLevel2>
      <someItem1>12345</someItem1>
      <someItem2 />
      <someItem3>11:20012:3536</someItem3>
      <someItem4 />
      <someItem5>someItem5 Data</someItem5>
      <someItem6>123456:USD</someItem6>
    </SomeLevel2>
    <SomeLevel3>
      <SomeLevel4>
        <SomeLevel5>
          <someItem6>303.149</someItem6>
          <someItem7>117:USD</someItem7>
          <someItem8>117.000000:USD</someItem8>
          <someItem9>117:USD</someItem9>
          <SomeLevel6 />
        </SomeLevel5>
        <SomeLevel7>
          <someItem10>292.741</someItem10>
          <someItem11>165:USD</someItem11>
          <someItem12>165.000000:USD</someItem12>
          <someItem13>165:USD</someItem13>
        </SomeLevel7>
        <SomeLevel8>
          <someItem14>369.075</someItem14>
          <someItem15>598:USD</someItem15>
          <someItem16>598.000000:USD</someItem16>
          <SomeLevel9>
            <SomeLevel10>
              <someItem17>Some Data | ABC 123</someItem17>
              <someItem18>2</someItem18>
            </SomeLevel10>
          </SomeLevel9>
          <SomeLevel10 />
        </SomeLevel8>
      </SomeLevel4>
    </SomeLevel3>
  </SomeLevel1>
</dataView>

注意:

有编号的元素名称(someItem1someItem6)会回来并最终咬你。 XML元素有一个自然的顺序(或者你可以有一个&#34;数字&#34;属性),将一个计数器放入名称是坏的和错误的。听取我的意见,不要那样做(*)

要理解这里的解决方案,请快速分解:

  • XSLT处理器通过模板运行XML节点,找到手头XML节点的最佳匹配。
  • 该过程从根节点开始。
  • 由于没有明确匹配根节点(<xsl:template match="/">)的模板,因此默认规则启动:不输出任何内容,但查找子节点的模板。
  • 第一个(也是唯一的)子节点是文档元素(<ds:dataView>)。
  • 模板#1匹配该节点,告诉处理器复制它并处理其子节点(<xsl:apply-templates />)。
  • 具有@name的每个元素都与模板#2匹配,模板#2输出具有该名称的元素并再次处理其子元素。
  • 所有其他元素(如<value>个节点) - 在没有任何匹配模板的情况下 - 根据提到的默认规则进行处理。
  • 文本节点由模板#3匹配,模板#3输出其修剪值。

附加说明:

  • 花括号中的表达式称为属性值模板
  • 模板priority="1"确保为<ds:dataView>元素选择了此模板,因为另一个元素也会匹配。
  • 您的结果文档仍在"http://component.mycompany.com/entity/ds"中。这可能是也可能不正确。从技术上讲,我怀疑它不正确,但你决定了。

(*) <xsl:element name="{translate(@name, '0123456789', '')}"将是失去计数器的一种变体。

答案 1 :(得分:0)

XSLT已经完全针对这样的任务创建了。只要你的Source-XML(非常规xml)格式正确(正确的xml语法),以便它可以被标准的xml-parser(如DOM)读取,你就可以使用它。

它的工作原理如下:您创建一个xsl-template文件,其中包含一个描述源xml应如何转换为另一种格式的描述。转换本身由XSL-Transformer完成。 xsl也是一个xml格式,因此只要转换不是太复杂,它就应该易于读取。

这里解释了如何实现: http://docs.oracle.com/javase/tutorial/jaxp/xslt/transformingXML.html