开发者

Remove all Artist node from an XML file

开发者 https://www.devze.com 2023-02-23 00:15 出处:网络
I have an XmlWriter that contains a xml that looks like the one below, just with a lot more nodes. what开发者_运维知识库\'s the fastest and best way to remove all the ARTIST node from this xml ?

I have an XmlWriter that contains a xml that looks like the one below, just with a lot more nodes. what开发者_运维知识库's the fastest and best way to remove all the ARTIST node from this xml ?

<CATALOG> 
  <CD> 
    <TITLE>Empire Burlesque</TITLE> 
    <ARTIST>Bob Dylan</ARTIST> 
  </CD> 
  <CD> 
    <TITLE>Hide your heart</TITLE> 
    <ARTIST>Bonnie Tyler</ARTIST>
  </CD>
</CATALOG> 


As long as the file isn't gigabytes XmlDocument should be fine:

    XmlDocument XDoc = new XmlDocument();
    XDoc.Load(MapPath(@"~\xml\test.xml"));

    XmlNodeList Nodes = XDoc.GetElementsByTagName("ARTIST");

    foreach (XmlNode Node in Nodes)
        Node.ParentNode.RemoveChild(Node);

    XDoc.Save(MapPath(@"~\xml\test_out.xml"));


When I tried Steve's solution I received the following error "The element list has changed. The enumeration operation failed to continue". I know it is a bit of a hack but to get around this I used the following:

//Load XML
XmlDocument XDoc = new XmlDocument();
XDoc.Load(MapPath(@"~\xml\test.xml"));

//Get list of offending nodes
XmlNodeList Nodes = XDoc.GetElementsByTagName("ARTIST");

//Loop through the list
while (Nodes.Count != 0) {
    foreach (XmlNode Node in Nodes) {
        //Remove the offending node
        Node.ParentNode.RemoveChild(Node); //<--This line messes with our iteration and forces us to get a new list after each remove
        //Stop the loop
        break;
    }
    //Get a refreshed list of offending nodes
    Nodes = XDoc.GetElementsByTagName("ARTIST");
}
//Save the document
XDoc.Save(newfile);

I was in a bind and needing something quick and this got the job done.


From the way your question is worded, I'm assuming that you have an XmlWriter that has been used to write an XmlDocument and you want to manipulate what it is going to write before flush is called.

I'm afraid that what you're trying to do may be impossible. The XmlWriter is not meant to manipulate XML before it is written to a destination stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号