c# – 如果xmldocument中存在属性,则删除该属性

前端之家收集整理的这篇文章主要介绍了c# – 如果xmldocument中存在属性,则删除该属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果文档中存在属性,如何从XmlDocument中删除属性?请帮忙.我正在使用RemoveAttribute但是如何检查它是否存在.

root.RemoveAttribute(fieldName的);

谢谢..

<?xml version="1.0" standalone="yes" ?> 
 <Record1>
  <Attribute1 Name="DataFieldName" Value="Pages" /> 
 </Record1>

我想删除名为“DataFieldName”的属性.

解决方法

不确定你想要做什么,所以这里有两个例子.

删除属性

var doc = new System.Xml.XmlDocument();
doc.Load("somefile.xml");
var root = doc.FirstChild;

foreach (System.Xml.XmlNode child in root.ChildNodes)
{
    if (child.Attributes["Name"] != null)
        child.Attributes.Remove(child.Attributes["Name"]);
}

属性设置为空字符串:

var doc = new System.Xml.XmlDocument();
doc.Load("somefile.xml");
var root = doc.FirstChild;

foreach (System.Xml.XmlNode child in root.ChildNodes)
{
    if (child.Attributes["Name"] != null)
        child.Attributes["Name"].Value = "";
}

编辑:如果您详细说明原始请求,我可以尝试修改我的代码. XML文档只能有一个根节点,而您的根节点似乎是record1.那么这是否意味着您的整个文件只包含一条记录?或者你的意思是有类似的东西

<?xml version="1.0" standalone="yes" ?>
<Records>
    <Record>
        <Attribute Name="DataFieldName" Value="Pages" />
    </Record>
    <Record>
        <Attribute Name="DataFieldName" Value="Pages" />
    </Record>
</Records>
原文链接:https://www.f2er.com/csharp/97613.html

猜你在找的C#相关文章