从根元素中删除XMLNS

本文关键字:删除 XMLNS 元素 | 更新日期: 2023-09-27 18:02:06

新建在这里,希望得到一点帮助与我的XmlDocument。是否有可能在我的根元素中有字符串数据并删除xmlns=属性?我在找这样的东西:

<Rulebase author=yadda datetime=bingbang version=1.x </Rulebase>

当我尝试使用我的字符串数据时:

xmlDom.AppendChild(xmlDom.CreateElement("", "Rulebase", data));
XmlElement xmlRoot = xmlDom.DocumentElement;

它最终看起来像这样:

<Rulebase xmlns="version=0 author=username date=7/13/2011 </Rulebase>

并且它还附加xmlns="到所有其他节点。

从根元素中删除XMLNS

您正在使用的CreateElement重载将前缀作为其第一个参数,本地名称作为第二个参数,命名空间作为第三个参数。如果不想使用名称空间,就不要使用此重载。只使用使用本地名称作为唯一参数的那个。然后将数据分别添加为子元素和属性。

var xmlDom = new XmlDocument();
XmlElement root = xmlDom.CreateElement("Rulebase");
xmlDom.AppendChild(root);
XmlElement data = xmlDom.CreateElement("Data");
root.AppendChild(data);
XmlAttribute attribute = xmlDom.CreateAttribute("author");
attribute.Value = "username";
data.Attributes.Append(attribute);
attribute = xmlDom.CreateAttribute("date");
attribute.Value = XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind);
data.Attributes.Append(attribute);
Console.WriteLine(xmlDom.OuterXml);

创建(添加格式)

<Rulebase>
    <Data author="username" date="2011-07-13T22:44:27.5488853-04:00" />
</Rulebase>

使用XmlDocument生成XML是相当乏味的。在。net中有许多更好的方法,如XmlSerializerDataContractSerializer。您还可以使用Linq-to-Xml和XElement。或者您可以使用XmlWriter.Create()。很多选项