【问题标题】:What is the proper way to call getAttributeNS using Java DOM?使用 Java DOM 调用 getAttributeNS 的正确方法是什么?
【发布时间】:2013-02-26 21:07:49
【问题描述】:

我在从 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"),结果一样。

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

谢谢。

【问题讨论】:

  • 天哪,w3schools...

标签: java dom namespaces


【解决方案1】:

紧跟在DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();之后,添加dbFactory.setNamespaceAware(true);

【讨论】:

  • 成功了。谢谢。如果像 getAttributeNS() 这样的 DOM 'NS' 方法上的 Javadoc 提到了这一点,那就太好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多