java 为什么java中的getElementsByTagNameNS为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13166195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:43:30  来源:igfitidea点击:

Why is the getElementsByTagNameNS empty in java?

javaxml

提问by user1512895

I want to get the value out tag2 and I got this a xml:

我想从 tag2 中取出值,我得到了一个 xml:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<ns1:schema xmlns:ns1='http://example.com'>" +
                "<ns1:tag1>" +
                "    <ns1:tag2>value</ns1:tag2>" +
                "</ns1:tag1>" +
            "</ns1:schema>"; 

Then parse it to a document and want to get the elements by tagnameNS. But when I run this the nodelist is empty why?

然后解析成文档,想通过tagnameNS获取元素。但是当我运行这个时,节点列表是空的,为什么?

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(xml))); 

        NodeList nl = doc.getElementsByTagNameNS("http://example.com", "tag2");

        String a = nl.item(0).getNodeValue();

Still doesnt work with the URI.

仍然不适用于 URI。

回答by bdoughan

getElementsByTagNameNSis returing a result. The issue is that you're currently calling the wrong method to get the text content off the result elements. You need to call getTextContext()and not getNodeValue()

getElementsByTagNameNS正在返回结果。问题是您当前调用了错误的方法来从结果元素中获取文本内容。你需要打电话getTextContext()而不是getNodeValue()

String a = nl.item(0).getTextContent();

DomDemo

演示

Below is a complete code example.

下面是一个完整的代码示例。

package forum13166195;

import java.io.StringReader;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class DomDemo {

    public static void main(String[] args) throws Exception{
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                   + "<ns1:schema xmlns:ns1='http://example.com'>"
                       + "<ns1:tag1>"
                           + "<ns1:tag2>value</ns1:tag2>"
                       + "</ns1:tag1>"
                   + "</ns1:schema>";

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(xml))); 

        NodeList nl = doc.getElementsByTagNameNS("http://example.com", "tag2");

        String a = nl.item(0).getTextContent();
        System.out.println(a);
    }

}

Output

输出

value


ALTERNATE APPROACH

替代方法

You can also use the javax.xml.xpathAPIs (included in Java SE 5 and above) to query a value from an XML document. These APIs offer a lot more control than getElementsByTagNameNS.

您还可以使用javax.xml.xpathAPI(包含在 Java SE 5 及更高版本中)从 XML 文档查询值。这些 API 提供了比getElementsByTagNameNS.

XPathDemo

XPathDemo

package forum13166195;

import java.io.StringReader;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;

import org.xml.sax.InputSource;

public class XPathDemo {

    public static void main(String[] args) throws Exception{
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                   + "<ns1:schema xmlns:ns1='http://example.com'>"
                       + "<ns1:tag1>"
                           + "<ns1:tag2>value</ns1:tag2>"
                       + "</ns1:tag1>"
                   + "</ns1:schema>";

        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new NamespaceContext() {

            public String getNamespaceURI(String arg0) {
                if("a".equals(arg0)) {
                    return "http://example.com";
                }
                return null;
            }

            public String getPrefix(String arg0) {
                return null;
            }

            public Iterator getPrefixes(String arg0) {
                return null;
            }

        });

        InputSource inputSource = new InputSource(new StringReader(xml));
        String result = (String) xpath.evaluate("/a:schema/a:tag1/a:tag2", inputSource, XPathConstants.STRING);
        System.out.println(result);
    }

}

Output

输出

value

回答by Nadhu

 Try this :

  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
  docBuilderFactory.setNamespaceAware(true);
  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
  Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));      
  NodeList nodeList = doc.getElementsByTagNameNS("*", "tag2");
  String a = nodeList.item(0).getTextContent();
  System.out.println(a);

Output

输出

value

回答by SLaks

You need to pass the namespace URL; not the local alias you created in the XML.

您需要传递命名空间 URL;不是您在 XML 中创建的本地别名。