I have a question related to the removal of certain nodes from an xml file.
Here is my XML example:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<nodeA attribute="1">
<nodeB attribute="table">
<nodeC attribute="500"></nodeC>
<nodeC attribute="5"></nodeC>
</nodeB>
<nodeB attribute="3">
<nodeC attribute="4"></nodeC>
<nodeC attribute="5"></nodeC>
<nodeC attribute="5"></nodeC>
</nodeB>
<nodeB attribute="placeHolder">
<nodeB attribute="toRemove">
<nodeB attribute="glass"></nodeB>
<nodeE attribute="7"></nodeE>
<nodeB attribute="glass"></nodeB>
<nodeB attribute="glass"></nodeB>
</nodeB>
</nodeB>
<nodeB attribute="3">
<nodeC attribute="4"></nodeC>
<nodeC attribute="5"></nodeC>
<nodeC attribtue="5"></nodeC>
</nodeB>
<nodeB attribute="placeHolder">
<nodeB attribute="toRemove">
<nodeB attribute="glass"></nodeB>
<nodeE attribute="7"></nodeE>
<nodeB attribute="glass"></nodeB>
<nodeB attribute="glass"></nodeB>
</nodeB>
</nodeB>
</nodeA>
</root>
I would like to remove a node nodeB="toRemove"without deleting the children of this node. After that I need to do the same with nodeB attribute="placeHolder". Part of the result will look like this:
<nodeB attribute="3">
<nodeC attribute="4"></nodeC>
<nodeC attribute="5"></nodeC>
<nodeC attribtue="5"></nodeC>
</nodeB>
<nodeB attribute="glass"></nodeB>
<nodeE attribute="7"></nodeE>
<nodeB attribute="glass"></nodeB>
<nodeB attribute="glass"></nodeB>
I am trying to make such code this way:
XmlNodeList nodeList = doc.SelectNodes("//nodeB[@attribute=\"toRemove\"]");
foreach (XmlNode node in nodeList)
{
foreach (XmlNode child in node.ChildNodes)
{
node.ParentNode.AppendChild(child);
}
node.ParentNode.RemoveChild(node);
}
doc.Save(XmlFilePathSource);
I can find a node with the desired attribute for Remove or placeHolder, however I cannot move the child nodes of these nodes one level. Could you help me in this case? It may be a solution with Linq, XDocument, XmlReader, but I prefer to work with XmlDocument. Thanks for any help you could provide me in advance.
EDIT:
( ), Chuck Savage .
<nodeB attribute="toRemove"> </nodeB>
<nodeB attribute="placeHolder"></nodeB>
XElement root = XElement.Load(XmlFilePathSource);
var removes = root.XPathSelectElements("//nodeB[@attribute=\"toRemove\"]");
foreach (XElement node in removes.ToArray())
{
node.Parent.AddAfterSelf(node.Elements());
node.Remove();
}
root.Save(XmlFilePathSource);
xslt , @MiMo, .