我应该如何使用org.w3c.dom.Node.getNamedItemNS(nsUri,name)选择XML“命名空间”节点?

时间:2010-07-31 00:03:24

标签: java xml namespaces

这是xml:

<xml xmlns:log="http://sample.com">

  <test log:writer="someWriter" />

</xml>

我正在尝试使用以下代码行获取“log:writer”的属性值:

currentNode.getAttributes().getNamedItemNS("log", "writer")

我还尝试在“test”节点上放置xmlns:log =“http://sample.com”声明,但我总是收到NullPointerExceptionDocumentBuilderFactory使用的Document也启用了setNamespaceAware。任何提示?

1 个答案:

答案 0 :(得分:4)

getNamedItemNS将namespaceURI作为其第一个参数(即http://sample.com),而不是前缀(log)。

修改

这是一个完整的测试用例。这打印出“属性值是someWriter”。使用Xerces作为XML库进行测试。这对你有用吗?

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class GetNamedItemNSTester
{
    public static void main(String[] args)
    {
        new GetNamedItemNSTester();     
    }

    String xml = "<xml xmlns:log=\"http://sample.com\">\n" +
            "\n" +
            "<test log:writer=\"someWriter\" />\n" +
            "\n" +
            "</xml>";


    public GetNamedItemNSTester()
    {
        StringReader xmlReader = new StringReader(xml);
        try
        {
            DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(xmlReader));

            Element currentNode =
                (Element)doc.getElementsByTagName("test").item(0);
            String attributeValue = currentNode.getAttributes()
                .getNamedItemNS("http://sample.com", "writer").getNodeValue();
            System.out.println("Attribute value is " + attributeValue);
        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (SAXException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            xmlReader.close();
        }
    }
}