Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用xpath解析xml并获取嵌套的child_Java_Xml_Xpath - Fatal编程技术网

Java 使用xpath解析xml并获取嵌套的child

Java 使用xpath解析xml并获取嵌套的child,java,xml,xpath,Java,Xml,Xpath,所以,我有一个XML结构,看起来像这样 <root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org"> <actors> <actorUID>1w2e3r</actorUID> <actor id="1"> <name>Christian Bale</name>

所以,我有一个XML结构,看起来像这样

<root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
    <actors>
        <actorUID>1w2e3r</actorUID>
        <actor id="1">
            <name>Christian Bale</name>
            <age>40</age>
        </actor>
        <actor id="2">
            <name>LiamNeeson</name>
            <age>45</age>
        </actor>
        <actor id="3">
            <name>Michael</name>
            <age>60</age>
        </actor>
    </actors>
    <foo:singers>
        <foo:singer id="4">
            <name>Michael</name>
            <age>60</age>
        </foo:singer>
        <foo:singer id="5">
            <name>Michael</name>
            <age>60</age>
        </foo:singer>
        <foo:singer id="6">
            <name>Michael</name>
            <age>60</age>
        </foo:singer>
    </foo:singers>
</root>

1w2e3r
克里斯蒂安·贝尔
40
债务
45
迈克尔
60
迈克尔
60
迈克尔
60
迈克尔
60
我需要解析这个json并将actorUID、actor.name、actor.age、foo:singers.name、foo:singers.age的元素保存到数据库中

我试过这个:

try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(stops));
                Document doc = db.parse(is);
                XPathFactory xPathfactory = XPathFactory.newInstance();
                XPath xpath = xPathfactory.newXPath();
                XPathExpression expr = xpath.compile("/root/actors");
                NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

                for (int i = 0; i < nl.getLength(); i++) {
                    Element element = (Element) nl.item(i);
                    System.out.println(element.getElementsByTagName("actorsUID")
                            .item(0)
                            .getTextContent());
                    System.out.println(element.getElementsByTagName("actor")
                            .item(0)
                            .getTextContent());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
试试看{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
InputSource is=新的InputSource();
is.setCharacterStream(新StringReader(停止));
文档doc=db.parse(is);
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile(“/root/actors”);
NodeList nl=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
对于(int i=0;i
在我得到这个-
元素后,如何才能得到演员名。getElementsByTagName(“演员”)
?


我不想只获取name元素,因为如果我必须将另一个孩子交给演员,如果它将具有actor.name,那么它将崩溃

实际上,我建议实现一个SAX解析器。但如果要使用xpath,需要注意两件事:

  • DocumentBuilderFactory必须知道名称空间

  • xpath必须使用名称空间上下文

您可以将它们设置为:

dbf.setNamespaceAware(true);

javax.xml.namespace.NamespaceContext ns = new javax.xml.namespace.NamespaceContext()
{

    @Override
    public String getNamespaceURI(String prefix) 
    {
        if ( "foo".equals( prefix ) )
        {
            return "http://www.foo.org/";
        }
        else if ( "bar".equals( prefix ) )
        {
            return "http://www.bar.org/";
        }
        else if ( "xml".equals( prefix ) )
        {
            return javax.xml.XMLConstants.XML_NS_URI;
        }

        return javax.xml.XMLConstants.NULL_NS_URI;

    }

    @Override
    public String getPrefix(String namespaceURI) {
        return null;
    }

    @Override
    public Iterator<?> getPrefixes(String namespaceURI) {
        return null;
    }

};

xpath.setNamespaceContext(ns);
for (int i = 0; i < nl.getLength(); i++) 
{
     Element element = (Element) nl.item(i);
     NodeList uids = element.getElementsByTagName("actorUID");
     for ( int j = 0; j < uids.getLength(); j++ )
     {
        System.out.println( "Actor UID : " + uids.item(j).getTextContent());
     }
     NodeList actors = element.getElementsByTagName("actor");
     for ( int j = 0; j < actors.getLength(); j++ )
     {
        NodeList cNodes = actors.item(j).getChildNodes();
        for ( int k = 0; k < cNodes.getLength(); k++ )
        {
            Node node = cNodes.item(k);
            if ( node.getNodeType() == Node.ELEMENT_NODE )
            {
                System.out.println( cNodes.item(k).getNodeName() + " : " + cNodes.item(k).getTextContent() );
            }

        }
     }
}