gpt4 book ai didi

java - 如何将命名空间声明添加到 DOM 的根元素?

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:50 25 4
gpt4 key购买 nike

我需要(嗯,真的很想...)将命名空间声明添加到 DOM 树的根元素。我稍后在文档中重复使用该 namespace ,并且在使用它的每个节点中都进行声明并不是很方便:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><test>
<value xmlns:test="urn:mynamespace" test:id="1">42.42</value>
<value2 xmlns:test="urn:mynamespace" test:id="2">Hello Namespace!</value2>
</test>

我想要得到的是

<?xml version="1.0" encoding="UTF-8" standalone="no"?><test xmlns:test="urn:mynamespace">
<value test:id="1">42.42</value>
<value2 test:id="2">Hello Namespace!</value2>
</test>

以后手动编辑时更加方便。

我知道这是可能的,因为这是我加载包含的文档时得到的结果

<test xmlns:test="urn:mynamespace">
</test>

并添加剩余的节点。

所以我认为问题归结为:如何将 xmlns:test="urn:mynamespace"添加到根节点?当我尝试添加属性时,我收到 NAMESPACE_ERR 异常(我使用命名空间感知工厂等)。因为我试图绕过我找不到的 API 来搞乱 namespace ...

注意:根元素中没有使用命名空间的属性(当我允许时,我可以让它工作),而只是命名空间声明。

最佳答案

使用此 XSLT 文档

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:test="urn:mynamespace">

<xsl:output indent="yes" standalone="no" encoding="UTF-8"/>

<!-- Copies root element and its contents -->
<xsl:template match="/*" priority="2">
<xsl:element name="{name()}" namespace="{namespace-uri()}">
<xsl:copy-of select="namespace::*"/>
<xsl:copy-of select="document('')/*/namespace::*[name()='test']"/>
<xsl:copy-of select="@*"/>
<xsl:copy-of select="*"/>
</xsl:element>
</xsl:template>

<!-- Copies comments, processing instructions etc. outside
the root element. This is not neccesarily needed. -->
<xsl:template match="/node()">
<xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

给定此输入(您的代码示例)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<test>
<value xmlns:test="urn:mynamespace" test:id="1">42.42</value>
<value2 xmlns:test="urn:mynamespace" test:id="2">Hello Namespace!</value2>
</test>

产生所需的输出

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<test xmlns:test="urn:mynamespace">
<value test:id="1">42.42</value>
<value2 test:id="2">Hello Namespace!</value2>
</test>

您可以使用 Transformer 类在 Java 中执行 XSLT 转换。

javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile);
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);

其中 xsltFile 是指向该 XSLT 文件的 File 对象。

关于java - 如何将命名空间声明添加到 DOM 的根元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22482350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com