remove attribute if it exists from xmldocument

2020-03-17 05:11发布

问题:

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);

Thanks..

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

I am trying to remove attribute named "DataFieldName".

回答1:

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

Removing the attribute:

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 = "";
}

Edit: 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>


回答2:

youcan use XmlNamedNodeMap.RemoveNamedItem Method (name) to do it. It can be used to Attributes.It will return the XmlNode removed from this XmlNamedNodeMap or a null reference (Nothing in Visual Basic) if a matching node was not found.

    [C#] 
    using System;
    using System.IO;
    using System.Xml;

   public class Sample
   {
    public static void Main()
    {
     XmlDocument doc = new XmlDocument();
     doc.LoadXml("<book genre='novel' publicationdate='1997'> " +
                 "  <title>Pride And Prejudice</title>" +
                 "</book>");      

     XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;

     // Remove the publicationdate attribute.
     attrColl.RemoveNamedItem("publicationdate");

     Console.WriteLine("Display the modified XML...");
     Console.WriteLine(doc.OuterXml);

     }
   }