尝试用Java解析org.w3c.dom.Document XML文档

时间:2017-09-21 10:57:02

标签: java xml

我正在尝试从String标签中获取数字。现在,Java程序认为字符串标记包含null。感谢您的帮助!

这是XML

@Value({"reports.PnLReport.reportId"})
private final String reportId;

这是我尝试过的

<?xml version="1.0"?>
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>6540321</string>
  <string>6540322</string>
  <string>6540323</string>
  <string>6540324</string>
  <string>6540325</string>
</ArrayOfstring>

输出:

public static void toOrderListFromXML() throws ParserConfigurationException, SAXException, IOException {
    File fXmlFile = new File("test.xml");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    org.w3c.dom.Document doc = dBuilder.parse(fXmlFile);

    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("string");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;

            System.out.println("Order number: " + eElement.getNodeValue());
        }
    }
}

以下是我尝试遵循的教程:http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

2 个答案:

答案 0 :(得分:1)

您可以尝试使用.getTextContent()

另见:Getting XML Node text value with Java DOM

答案 1 :(得分:1)

public static void toOrderListFromXML() throws ParserConfigurationException, 
    SAXException, IOException {
        File fXmlFile = new File("test.xml");

        DocumentBuilderFactory dbFactory = 
   DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    org.w3c.dom.Document doc = dBuilder.parse(fXmlFile);

    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + 
   doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("string");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;

            System.out.println("Order number: " + 
          eElement.getTextContent());
         }
     }
   }
 }

然后输出

Root element :ArrayOfstring

Current Element :string
Order number: 6540321

Current Element :string
Order number: 6540322

Current Element :string
Order number: 6540323

Current Element :string
Order number: 6540324

Current Element :string
Order number: 6540325