如果属性存在于xmldocument中,则将其移除 [英] remove attribute if it exists from xmldocument

查看:47
本文介绍了如果属性存在于xmldocument中,则将其移除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文档中存在属性,如何从XmlDocument中删除该属性?请帮忙.我正在使用RemoveAttribute,但是如何检查它是否存在.

How to remove the attribute from XmlDocument if attribute exists in the document? Please help. I am using RemoveAttribute but how can I check if it exists.

root.RemoveAttribute(fieldName);

root.RemoveAttribute(fieldName);

谢谢..

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

我正在尝试删除名为"DataFieldName"的属性.

I am trying to remove attribute named "DataFieldName".

推荐答案

不确定确切要执行的操作,因此有两个示例.

Not sure exactly what you're trying to do, so here's two examples.

删除属性:

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"]);
}

将属性设置为空字符串:

Setting the attribute to an empty string:

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.那么这是否意味着您的整个文件将仅包含一条记录?还是你想拥有类似的东西

I can try to modify my code if you elaborate on your original request. An XML document can only have one root node and yours appears to be record1. So does that mean your entire file will only contain a single record? Or did you mean to have something like

<?xml version="1.0" standalone="yes" ?>
<Records>
    <Record>
        <Attribute Name="DataFieldName" Value="Pages" />
    </Record>
    <Record>
        <Attribute Name="DataFieldName" Value="Pages" />
    </Record>
</Records>

这篇关于如果属性存在于xmldocument中,则将其移除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆