Reputation: 2790
I am trying to remove some specified attributed from the XML file sample code was below. string[] szNodeList is the array list so node contains name in string array will be removed ans save again
Any help will be appreciated.
var doc = new System.Xml.XmlDocument();
doc.Load("attrs.xml");
var root = doc.DocumentElement;
string[] szNodeList = new string[] { "titleTextColor"
,"isLightTheme"
,"showText"
};
foreach (System.Xml.XmlElement child in root )
{
foreach (string sz in szNodeList)
{
root.RemoveAttribute(sz);
//if (child.Attributes[sz] != null)
//{
// child.Attributes.Remove(child.Attributes[sz]);
//}
}
}
doc.Save("build.xml");
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="cropImageStyle" format="reference" />
<attr name="drawerArrowStyle" format="reference" />
<attr name="height" format="dimension" />
<attr name="isLightTheme" format="boolean" />
<attr name="title" format="string" />
<attr name="navigationMode">
<enum name="listMode" value="1" />
<enum name="normal" value="0" />
<enum name="tabMode" value="2" />
</attr>
</resources>
But saving as original file without changes i thing remove is not working.
Upvotes: 0
Views: 1927
Reputation: 1499870
One of the problems here is terminology. You're not trying to remove attributes, as I understand it - you're trying to remove whole elements, based on the value of the name
attribute.
If you can possibly use LINQ to XML for this, I would do so. It generally makes working with XML a lot easier. Here's a complete program to do what you want:
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
var namesToRemove = new[]
{
"titleTextColor",
"isLightTheme",
"showText"
};
XDocument doc = XDocument.Load("test.xml");
// For all the elements directly under the document root...
doc.Root.Elements()
// Where the array contains the value of the "name" attribute...
.Where(x => namesToRemove.Contains((string) x.Attribute("name")))
// Remove them from the document
.Remove();
doc.Save("output.xml");
}
}
Output:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="cropImageStyle" format="reference" />
<attr name="drawerArrowStyle" format="reference" />
<attr name="height" format="dimension" />
<attr name="title" format="string" />
<attr name="navigationMode">
<enum name="listMode" value="1" />
<enum name="normal" value="0" />
<enum name="tabMode" value="2" />
</attr>
</resources>
Upvotes: 1
Reputation: 14477
Try this:
doc
// select all `resources/attr` node
.SelectNodes("resources/attr")
.Cast<XmlNode>()
// that contains the `name` attribute whose value is in `szNodeList`
.Where(x => !string.IsNullOrEmpty(x.Attributes["name"]?.Value) && szNodeList.Contains(x.Attributes["name"].Value))
.ToList()
// and, remove them from their parent
.ForEach(x => x.ParentNode.RemoveChild(x));
Upvotes: 2