C# 从 XML 数据中删除命名空间引用和使用

问题描述 投票:0回答:1

我正在获取 Swift MX 消息,并且需要从中删除命名空间。本质上,它们是粘合在一起的两个 XML 文档。大多数时候他们看起来像这样:

<AppHdr>
标题内容
</AppHdr><Document>
文档内容
</Document>

这很容易处理,因为我将

<root>
</root>
放在整个事物周围以生成 XML(仅一个根节点)并将其读入 XmlDocument:

<root><AppHdr>
...
</AppHdr><Document>
...
</Document></root>

但是,某些消息具有命名空间,并且命名空间在设计时是未知的。一个例子可能是:

<ns2:AppHdr xmlns:ns2="some stuff">
标题内容
</ns2:AppHdr><ns3:Document xmlns:ns3="some other stuff">
文档内容
</ns3:Document>

请注意,

AppHdr
下的所有 XML 树都引用
AppHdr
的命名空间标记,而
Document
下的所有 XML 树都引用
Document
的命名空间标记。

命名空间标签可能会有所不同。在这个例子中,它们是

ns2
ns3
,但我不知道它们会是什么。有没有简单的方法可以去掉这些?

c# xml string
1个回答
0
投票

未提供最小的可重现示例。这是一个基于 XSLT 的概念性解决方案,适用于任何格式良好的 XML 文件。

输入XML

<root>
   <ns2:AppHdr xmlns:ns2="some stuff">*contents of the header*</ns2:AppHdr>
   <ns3:Document xmlns:ns3="some other stuff">*contents of the document*</ns3:Document>
</root>

XSLT

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
   <xsl:strip-space elements="*"/>

   <!-- template to copy elements -->
   <xsl:template match="*">
      <xsl:element name="{local-name()}">
         <xsl:apply-templates select="@* | node()"/>
      </xsl:element>
   </xsl:template>

   <!-- template to copy attributes -->
   <xsl:template match="@*">
      <xsl:attribute name="{local-name()}">
         <xsl:value-of select="."/>
      </xsl:attribute>
   </xsl:template>

   <!-- template to copy the rest of the nodes -->
   <xsl:template match="comment() | text() | processing-instruction()">
      <xsl:copy/>
   </xsl:template>
</xsl:stylesheet>

输出XML

<root>
  <AppHdr>*contents of the header*</AppHdr>
  <Document>*contents of the document*</Document>
</root>
© www.soinside.com 2019 - 2024. All rights reserved.