使用Java DOM调用getAttributeNS的正确方法是什么?

时间:2013-02-26 21:07:49

标签: java dom namespaces

我遇到了从Java DOM正确调用getAttributeNS()(以及其他NS方法)的问题。首先,这是我的示例XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book xmlns:c="http://www.w3schools.com/children/" xmlns:foo="http://foo.org/foo" category="CHILDREN">
        <title foo:lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
</bookstore>

这是我的小Java类,它使用DOM并调用getAttributeNS:

package com.mycompany.proj;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.io.File;

public class AttributeNSProblem
{
    public static void main(String[] args)
    {
        try
        {
            File fXmlFile = new File("bookstore_ns.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

            NodeList nList = doc.getElementsByTagName("title");
            Element elem = (Element)nList.item(0);
            String lang = elem.getAttributeNS("http://foo.org/foo", "lang");
            System.out.println("title lang: " + lang);
            lang = elem.getAttribute("foo:lang");
            System.out.println("title lang: " + lang);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

当我调用getAttributeNS(&#34; http://foo.org/foo&#34;,&#34; lang&#34;)时,它返回一个空字符串。我也试过getAttributeNS(&#34; foo&#34;,&#34; lang&#34;),结果相同。

检索由命名空间限定的属性值的正确方法是什么?

感谢。

1 个答案:

答案 0 :(得分:1)

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();之后,立即添加dbFactory.setNamespaceAware(true);