开发者

C# consolidate namespace references in xml

开发者 https://www.devze.com 2023-01-10 00:31 出处:网络
I have xml formatted by the atom formatter. The atom formatter seems to specify namespaces inline multiple times.

I have xml formatted by the atom formatter. The atom formatter seems to specify namespaces inline multiple times.

Is there any way to easily consolidate these. The example below shows namespaces specified three times for each property. This is horrible.

I 开发者_JS百科would like prefixes at the top of the document and no namespaces in the document (just prefixes). Is there a writer or formatter option to achieve this?

<property p3:name="firstname" xmlns:p3="http://a9.com/-/opensearch/extensions/property/1.0/" xmlns="http://a9.com/-/opensearch/extensions/property/1.0/">Drikie</property>

Thanks

Craig.


The atom formatter seems to specify namespaces inline multiple times.

Is there any way to easily consolidate these. The example below shows namespaces specified three times for each property. This is horrible.

The easiest way to produce this more compact format is to apply the following XSLT transformation on your XML document:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()[not(self::*)]|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="*">
  <xsl:element name="{name()}" namespace="{namespace-uri()}">
   <xsl:copy-of select="descendant::*/namespace::*"/>
   <xsl:copy-of select="namespace::*"/>

   <xsl:apply-templates select="node()|@*"/>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>

For example, when applied on the following XML document (based on your question):

<t xmlns="http://a9.com/-/opensearch/extensions/property/1.0/">
<property p3:name="firstname"
  xmlns:p3="http://a9.com/-/opensearch/extensions/property/1.0/"
  xmlns="http://a9.com/-/opensearch/extensions/property/1.0/"
  >Drikie</property>
</t>

the wanted result is produced:

<t
 xmlns="http://a9.com/-/opensearch/extensions/property/1.0/"
 xmlns:p3="http://a9.com/-/opensearch/extensions/property/1.0/">
    <property p3:name="firstname">Drikie</property>
</t>

Do note:

  1. A namespace declaration cannot be promoted further above an element that has a declaration that binds the same prefix to another namespace.

  2. Promoting a namespace declaration to an ancestor element may increase the size of the parsed XML document, because all namespace nodes are propagated down to all descendent nodes, some of which may not need at all that namespace.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号