XML 命名空间默认/继承 [英] XML namespace defaulting/inheritance

查看:37
本文介绍了XML 命名空间默认/继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的 XML 片段中,a、c、d 和 e 的命名空间是什么?参考文档或规范将不胜感激.

In the below XML snippet what are the namespaces of a, c, d and e? Reference to documentation or specifications would be appreciated.

<a xmlns="http://domain/a">
    <pre:b xmlns:pre="http://domain/b">
        <c/>
        <d xmlns="">
            <e/>
        </d>
    </pre:b>
</a>

此外,哪些 Java 框架尊重官方命名空间默认设置?我有 tride org.w2c.* DOM 包,但是它似乎没有正确解析命名空间 URI?例如,具有类似功能的东西.

Also, what Java frameworks respect the official namespace defaulting? I have tride org.w2c.* DOM packages, however it does not seem to resolve the namespace URI correctly? For example, something with similar functionality to.

String namespace = DocumentParser.parse().
                    getElement("a").
                    getElement("b").
                    getElement("c").
                    getNamespaceURI();

推荐答案

据我所知,Java 中的所有标准 XML API 都支持命名空间.许多 API 是在创建命名空间(或变得流行 - 我不再记得)之前编写的.您经常需要启用支持:

To the best of my knowledge, all the standard XML APIs in Java support namespaces. Many of the APIs were written before namespaces were created (or became popular - I can no longer remember). You often need to enable support:

public class NS {
  private static void print(Node node) {
    Queue<Node> nodes = new LinkedList<Node>();
    nodes.add(node);
    while (!nodes.isEmpty()) {
      node = nodes.poll();
      NodeList list = node.getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        nodes.add(list.item(i));
      }
      System.out.format("%s %s %s%n", node.getPrefix(), node.getLocalName(),
          node.getNamespaceURI());
    }
  }

  public static void main(String[] args) throws Exception {
    String xml = "<a xmlns=\"http://domain/a\">"
        + "<pre:b xmlns:pre=\"http://domain/b\">" + "<c/>" + "<d xmlns=\"\">"
        + "<e/>" + "</d>" + "</pre:b>" + "</a>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(
        new InputSource(new StringReader(xml)));
    print(doc.getDocumentElement());
  }
}

此代码将打印:

null a http://domain/a
pre b http://domain/b
null c http://domain/a
null d null
null e null

这篇关于XML 命名空间默认/继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆