【问题标题】:.NET XmlDocument: Including default namespace prefixes in OuterXml.NET XmlDocument:在 OuterXml 中包含默认命名空间前缀
【发布时间】:2015-05-15 01:19:05
【问题描述】:

我有一个包含以下 XML 的 XmlDocument 对象:

<root>
   <childlist xmlns:pre="mydomain.com">
     <pre:child someattribute="value" />
  </childlist>
</root>

以字符串形式接收 XML 文档的客户端应用程序要求元素具有“pre:”前缀。

我的问题是,当我使用 .OuterXml 方法从 XmlDocument 获取 XML 文本时,前缀被删除:

<root>
  <childlist xmlns:pre="mydomain.com">
    <child someattribute="value" />  <!--where's the prefix?-->
  </childlist>
</root>

我知道,从技术上讲,默认命名空间不需要前缀,但同样,接收此 XML 的客户端在没有前缀的情况下将无法工作。

当我使用调试器检查节点时,.Name 属性是“pre:child”。所以 XmlDocument 对象存储了前缀,它只是没有出现在 .OuterXml 中。

有没有办法序列化 XmlDocument 对象并包含元素名称前缀?

我已经使用了几种使用 XmlSerializer 和 XmlTextWriter 对象的方法,但我得到了相同的结果。也许 XmlDocument、XmlSerializer 或 XmlTextWriter 上有一个属性可以指定我希望将默认命名空间前缀包含在输出中?

(顺便说一句,如果您只是使用 .LoadXml() 将上述 XML 加载到 XmlDocument 对象中,则前缀将出现在 .OuterXml 中。只有在使用 .AppendNode() 构建文档时它们才会消失。)

【问题讨论】:

  • 您能否分享在获得.OuterXml 属性之前生成XML 文档的实际代码?

标签: .net xml namespaces


【解决方案1】:

找到了答案:

http://bytes.com/topic/c-sharp/answers/568487-inserting-xml-node-maintaining-prefix

它并不完美——它假定提供 NamespacedURI 的元素也需要前缀。但这是一个可行的开始。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,关键似乎是添加一个 XmlNode 作为 NodeType 元素。与直接添加为 XmlElement 相比。

    请注意,“urn:something:mapper:somethingelse:commontypes”将来自您的 XML 文档中指定的名称空间。

            XmlNodeList xNodSIDetails = xDoc.GetElementsByTagName("pt:SIDetails");
            // Select the parent node where you want to add the element
            XmlNode xSID = xNodSIDetails[0];
            // Select the peer node that you want to insert the element after.
            XmlNode xLotNum = xNodSIDetails[0].ChildNodes[3];
            // Create the node, of the type Element, with the name you want including the prefix and the namespace URI.
            XmlNode xn = xDoc.CreateNode(XmlNodeType.Element,"cmn:ExpirationDate", "urn:something:mapper:somethingelse:commontypes"); 
            //  Assign the Node the inner text value.
            xn.InnerText = "1999-03-24";
            //  Insert the node after the one you previous chose for this to follow.
            xSID.InsertAfter(xn, xLotNum);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 2017-01-11
      相关资源
      最近更新 更多