我已经编写了一个PowerShell脚本,该脚本可以查看XML并取消对某些项目的注释。我这样做的方法是删除注释并创建新XmlElement
对象来代替它。
我的问题是,当我将文件保存在现有文件上时,在XmlDocument
根元素中添加了额外的属性xmlns=""
。XmlDocument
在保存之前,我使用调试器查看了对象,而我的新元素OuterXml
具有以下结构:
<register type="IComStack" mapTo="ComStackEth">
<lifetime type="singleton" />
<constructor>
<param name="host" type="System.Net.IPAddress">
<value value="127.0.0.1" typeConverter="IPAddressTypeConverter" />
</param>
</constructor>
</register>
保存后,我查看文件,并且我的元素如下所示:
<register type="IComStack" mapTo="ComStackEth" xmlns="">
<lifetime type="singleton" />
<constructor>
<param name="host" type="System.Net.IPAddress">
<value value="127.0.0.1" typeConverter="IPAddressTypeConverter" />
</param>
</constructor>
</register>
然后,我回到调试器,再次查看我的元素,然后以正确的格式(即没有xmlns属性)看到它。
我使用$config.Save($configPath)
top保存我的xml并使用以下命令加载它:
$config= new-object System.Xml.XmlDocument
$config.Load($configPath)
有谁知道我可以防止XmlDocument.Save
添加名称空间属性吗?
有谁知道我可以防止
XmlDocument.Save
添加名称空间属性吗?
通过在正确的命名空间中创建元素。
孤立地,XML文档
<register type="IComStack" mapTo="ComStackEth">
<lifetime type="singleton" />
<constructor>
<param name="host" type="System.Net.IPAddress">
<value value="127.0.0.1" typeConverter="IPAddressTypeConverter" />
</param>
</constructor>
</register>
包含许多具有各种本地名称且没有名称空间的元素。和XML文档
<root xmlns="http://example.com">
<!-- content goes here -->
</root>
包含root
在http://example.com
命名空间中命名的元素。如果要将子节点添加到此root
元素,而这些节点不在http://example.com
名称空间中,则序列化程序必须添加合适的名称空间声明-如果未添加,xmlns=""
则结果将不正确,因为以前没有名称空间的元素将“移动”到http://example.com
命名空间中。
<root xmlns="http://example.com">
<register type="IComStack" mapTo="ComStackEth" xmlns="">
<lifetime type="singleton" />
<constructor>
<param name="host" type="System.Net.IPAddress">
<value value="127.0.0.1" typeConverter="IPAddressTypeConverter" />
</param>
</constructor>
</register>
</root>
因此,实际上,根据XML名称空间的规则,调试器和最终XML文档都是正确的。
如果要避免添加序列化程序,xmlns=""
则需要确保要插入的节点使用与要添加到其的父元素相同的名称空间创建。到底如何实现取决于您如何创建XmlElement
对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句