0

我在从 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>

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

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(" http://foo.org/foo ", "lang") 时,它返回一个空字符串。我也试过 getAttributeNS("foo", "lang"),同样的结果。

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

谢谢。

4

1 回答 1

1

紧接着DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();,添加dbFactory.setNamespaceAware(true);

于 2013-02-27T07:52:09.260 回答