如何使用DOM API在Java中解析此xml?

时间:2014-02-26 12:56:28

标签: java xml parsing dom

我正在尝试解析xml文件,并希望只获取某些信息。

...
<field name="firstname">
    <value>John</value>
</field>
<field name="lastname">
    <value>Citizen</value>
</field>
<field name="DoB">
    <value>01/01/1980</value>
</field>
<field name="Profession">
    <value>"Manager"</value>
</field>
....

我有文档,现在我可以通过循环标记的NodeList打印出所有值,但是,我不知道如何获取特定值,例如我只想要列表中的姓氏和职业,所以我的目标是:“Citizen”和“Manager”

请提供任何线索。

谢谢

3 个答案:

答案 0 :(得分:1)

尝试使用DOM API(使用Document,Element和Node的方法),您可以非常快速地操作XML。

在下面的示例中,我将XML作为字符串加载,提取节点并将它们放在Map中。您可以将它作为编写代码的起点。我刚刚在您的XML中添加了<root>,因此我可以将代码放在一个工作示例中。

public class DOMExampleStackOverflow3 {

    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, TransformerException {

        InputSource source = new InputSource(new StringReader("<root>\n" +
                                                            "<field name=\"firstname\">\n" +
                                                            "    <value>John</value>\n" +
                                                            "</field>\n" +
                                                            "<field name=\"lastname\">\n" +
                                                            "    <value>Citizen</value>\n" +
                                                            "</field>\n" +
                                                            "<field name=\"DoB\">\n" +
                                                            "    <value>01/01/1980</value>\n" +
                                                            "</field>\n" +
                                                            "<field name=\"Profession\">\n" +
                                                            "    <value>Manager</value>\n" +
                                                            "</field>\n" +
                                                            "</root>" ));

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        Document document = documentBuilder.parse(source);

        NodeList allFields = (NodeList) document.getElementsByTagName("field");

        Map<String, String> data = new HashMap<>();
        for(int i = 0; i < allFields.getLength(); i++) {
            Element field = (Element)allFields.item(i);
            String nameAttribute = field.getAttribute("name");
            Element child = (Element)field.getElementsByTagName("value").item(0);
            String value = child.getTextContent();
            data.put(nameAttribute, value);
        }

        for(Map.Entry field : data.entrySet()) {
            System.out.println(field.getKey() + ": " + field.getValue());
        }
    }
}

结果是:

firstname: John
Profession: Manager
DoB: 01/01/1980
lastname: Citizen

现在,您可以更改代码,并在条件块提取中使用属性信息。

答案 1 :(得分:0)

您可能只使用XPath。以下是使用Xsylum的示例:

XmlDocument doc = Xsylum.documentFor(xml);
String lastName = doc.value("//field[@name='lastname']/value/text()");
String profession = doc.value("//field[@name='Profession']/value/text()");

答案 2 :(得分:-1)

Try This......


package com.mkyong.seo;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

    File fXmlFile = new File("/Users/mkyong/staff.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

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

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

    System.out.println("----------------------------");

    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("Staff id : " + eElement.getAttribute("id"));
            System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
            System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
            System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
            System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

}




For More Reference: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/