如何在单个节点中构建具有多个xml命名空间的XmlDocument?

时间:2021-01-09 22:46:29

I'm trying to build XmlDocument so that after serialization I could achieve something like this xml:

我正在尝试构建XmlDocument,以便在序列化后我可以实现类似这样的xml:

<?xml version="1.0" encoding="UTF-8"?>
<wnio:element xmlns:wnio="somuri" xmlns:xf="abcd">
   <xf:nestedelement>somtext</xf:nestedelement>
</wnio:element>

The things is that XmlElement allows to specify ONLY ONE namespace via NamespaceURI and Prefix properties. How can I accomplish this kind of functionality?

事情是XmlElement允许通过NamespaceURI和Prefix属性指定ONLY ONE命名空间。我怎样才能完成这种功能?

1 个解决方案

#1


The attributes "xmlns:wnio" and "xmlns:xf" are attributes like any other. Simply add them to the XmlElement that you would like these XML Namespaces to scope to.

属性“xmlns:wnio”和“xmlns:xf”是任何其他属性。只需将它们添加到您希望这些XML命名空间可以扩展到的XmlElement中。

The following snippet produces almost exactly what you want:

以下代码段几乎可以生成您想要的内容:

XmlDocument document = new XmlDocument();
document.AppendChild(document.CreateElement("wnio", "element", "somuri"));
document.DocumentElement.SetAttribute("xmlns:xf", "abcd");
document.DocumentElement.AppendChild(document.CreateElement("xf", "nestedelement", "abcd"));

#1


The attributes "xmlns:wnio" and "xmlns:xf" are attributes like any other. Simply add them to the XmlElement that you would like these XML Namespaces to scope to.

属性“xmlns:wnio”和“xmlns:xf”是任何其他属性。只需将它们添加到您希望这些XML命名空间可以扩展到的XmlElement中。

The following snippet produces almost exactly what you want:

以下代码段几乎可以生成您想要的内容:

XmlDocument document = new XmlDocument();
document.AppendChild(document.CreateElement("wnio", "element", "somuri"));
document.DocumentElement.SetAttribute("xmlns:xf", "abcd");
document.DocumentElement.AppendChild(document.CreateElement("xf", "nestedelement", "abcd"));