【问题标题】:Convert entire dom4j Element's namespace转换整个 dom4j 元素的命名空间
【发布时间】:2020-04-22 04:58:58
【问题描述】:

如果我有这样的 XML 元素:

<First id="" name="">
  <Second id="" name="">
  </Second>
</First>

如何使用 dom4j 将命名空间转换为如下所示的名称?有没有简单的方法?

<test:First test:id="" test:name="">
  <test:Second test:id="" test:name="">
  </test:Second>
</test:First>

【问题讨论】:

    标签: java xml dom4j


    【解决方案1】:

    如果您更喜欢以 Java 为中心的解决方案,DOM4J 支持遍历文档树:

        Document doc = DocumentHelper.parseText(XML);
        final Namespace ns = Namespace.get("test", "urn:foo:bar");
        doc.accept(new VisitorSupport() {
            @Override
            public void visit(Element node) {
                node.setQName(QName.get(node.getName(), ns));
                // Attribute QNames are read-only, so need to create new
                List<Attribute> attributes = new ArrayList<Attribute>();
                while(node.attributes().size() > 0)
                    attributes.add(node.attributes().remove(0));
                for(Attribute a: attributes) {
                    node.addAttribute(QName.get(a.getName(), ns), a.getValue());
                }
            }
        });
    

    【讨论】:

      【解决方案2】:

      您可以运行 XSLT 转换:

        <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
          <xsl:template match="*">
            <xsl:element name="test:{local-name()}" namespace="http://test-namepace/ns">
              <xsl:apply-templates select="@* | node()"/>
            </xsl:element>
          </xsl:template>
          <xsl:template match="@*">
            <xsl:attribute name="test:{local-name()}" namespace="http://test-namepace/ns">
              <xsl:value-of select="."/>
            </xsl:element>
          </xsl:template>
        </xsl:transform>
      

      我认为 DOM4J 具有直接应用 XSLT 1.0 转换的方法,但您也可以选择使用 Saxon,它将 DOM4J 与许多其他树模型一起处理为输入和/或输出。

      顺便说一下,(a) 在您的需求示例中,结果文档格式不正确,因为它没有声明命名空间,并且 (b) 将所有属性放在与包含元素;我给了你一个解决方案,假设你有充分的理由来设计这个相当奇怪的设计。

      【讨论】:

        猜你喜欢
        • 2016-04-18
        • 1970-01-01
        • 1970-01-01
        • 2020-03-24
        • 1970-01-01
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-20
        相关资源
        最近更新 更多