无法使用java在xpath中基于父属性值检索childelement

时间:2016-11-25 10:48:26

标签: java xpath

我正在尝试获取父节点的name元素,其属性值为FieldType my source xml如下所示。

<external xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Format" type="Format" version="0.0.1" formattype="Format">
    <header>
        <field xsi:type="FieldType">
            <name>Header Length</name>
        </field>
   </header>

  1. 下面是我的java代码

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = domFactory.newDocumentBuilder();
        Document document=builder.parse(file);
        XPath xPath =  XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new NamespaceContext() {
    
            public Iterator getPrefixes(String namespaceURI) {
                // TODO Auto-generated method stub
                return null;
            }
    
            public String getPrefix(String namespaceURI) {
                // TODO Auto-generated method stub
                return null;
            }
    
            public String getNamespaceURI(String prefix) {
                // TODO Auto-generated method stub
                if(prefix.equals("xsi")){
                    return "http://www.w3.org/2001/XMLSchema-instance";}else if(prefix.equals("type")){
                    return "Format";}
                return null;}
        });NodeList nodelist1=(NodeList)xPath.compile("//field[@xsi:type='FieldType']//name").evaluate(document,XPathConstants.NODESET);
        System.out.println("node1="+nodelist1.getLength());                           
    

0 个答案:

没有答案