如何从XML响应中解析/获取节点数据?

时间:2013-09-26 08:17:18

标签: xml

如何解析/获取位置节点值:新德里,印度使用循环,类似地如何从此xml文件中获取SVM,HHHHH等多个教育节点值。 XML:

<?xml version="1.0" encoding="UTF-8"?>
<facebookfriends>
<data>
<id>
[Removed]
    </id>
    <location>
        <id>
            [Removed]
        </id>
        <name>
            New Delhi, India
        </name>
    </location>
    <name>
        XYZZZZZZZZZZ
    </name>
    <education>
        <school>
            <id>
                [Removed]
            </id>
            <name>
                SVM
            </name>
        </school>
        <year>
            <id>
                [Removed]
            </id>
            <name>
                2001
            </name>
        </year>
        <type>
            High School
        </type>
    </education>
    <education>
        <concentration>
            <id>
                [Removed]
            </id>
            <name>
                Computer Science
            </name>
        </concentration>
        <school>
            <id>
                [Removed]
            </id>
            <name>
                HHHHHHHHHHHHH
            </name>
        </school>
        <type>
            Graduate School
        </type>
</education>
</data>

</facebookfriends>

2 个答案:

答案 0 :(得分:1)

你可以使用jDom ......简单易用...

http://www.mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/

请参阅以上链接以获取示例...

答案 1 :(得分:0)

下面的代码将帮助您通过解析从xml获取位置/名称节点值。同样,只需更改xpath即可获得其他节点值。

        File xmlFile = new File("C:/face.xml");
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try{
            builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(xmlFile);
            XPath xPath = XPathFactory.newInstance().newXPath();
            String exp = "/facebookfriends/data/location/name";
            NodeList nodeList = (NodeList) xPath.compile(exp).evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
            }
        }catch (ParserConfigurationException e) {
            e.printStackTrace();  
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }