我有一个包含以下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()构建文档时,它们才会消失。)
发布于 2015-03-13 03:37:42
似乎找到了答案:
http://bytes.com/topic/c-sharp/answers/568487-inserting-xml-node-maintaining-prefix
它并不完美--它假设提供NamespacedURI的元素也需要前缀。但这是一个可行的开始。
发布于 2018-04-11 02:25:39
我遇到了同样的问题,关键似乎是添加一个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);https://stackoverflow.com/questions/29017321
复制相似问题