簡體   English   中英

從XML文件中刪除所有Artist節點

[英]Remove all Artist node from an XML file

我有一個XmlWriter,它包含一個看起來像下面的xml,只是有更多的節點。 從這個xml中刪除所有ARTIST節點的最快和最好的方法是什么?

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

只要文件不是千兆字節,XmlDocument應該沒問題:

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

當我嘗試Steve的解決方案時,我收到以下錯誤“ 元素列表已更改。枚舉操作無法繼續 ”。 我知道這有點像黑客,但為了解決這個問題,我使用了以下內容:

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

我陷入困境,急需一些事情,這就完成了工作。

從你的問題措辭的方式來看,我假設你有一個XmlWriter用於編寫XmlDocument,你想在調用flush之前操縱它要寫的內容。

我擔心你想要做的事情可能是不可能的。 XmlWriter並不意味着在將XML寫入目標流之前對其進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM