开发者

Trying to use RemoveChild() on XmlNodeList messes up my XmlNode collection

开发者 https://www.devze.com 2022-12-23 15:45 出处:网络
I\'m trying to remove a spec开发者_如何转开发ific node from a XmlNodeList named listaWidths. This specific list has 5 items before I use RemoveChild(). But, after the RemoveChild() statement, the list

I'm trying to remove a spec开发者_如何转开发ific node from a XmlNodeList named listaWidths. This specific list has 5 items before I use RemoveChild(). But, after the RemoveChild() statement, the list stays only with 1 item.

XmlNodeList listaWidths = xmlDoc.SelectNodes("/MsBuild:Report/MsBuild:Body/MsBuild:ReportItems/MsBuild:Tablix/MsBuild:TablixBody/MsBuild:TablixColumns/*", nsmgr);                
int indexEpoca = 0;
XmlNode node = listaWidths[indexEpoca];
XmlNode parent = listaWidths[indexEpoca].ParentNode;
parent.RemoveChild(node);

This is a RDL Reporting Services XML. The specific XML code is here:

  <Tablix Name="Tablix3">
    <TablixBody>
      <TablixColumns>
        <TablixColumn>
          <Width>1.602in</Width>
        </TablixColumn>
        <TablixColumn>
          <Width>1.61in</Width>
        </TablixColumn>
        <TablixColumn>
          <Width>1.6323in</Width>
        </TablixColumn>
        <TablixColumn>
          <Width>1.6023in</Width>
        </TablixColumn>
        <TablixColumn>
          <Width>1.6033in</Width>
        </TablixColumn>
      </TablixColumns>
      (...)

I've tried every combination possible, with no luck whatsoever. What am I doing wrong? Thank you.


The documentation of SelectNodes clearly says: "The XmlNodeList object returned by this method will be valid while the underlying document remains unchanged. If the underlying document changes, unexpected results may be returned (no exception will be thrown)."

So what you experience with your XmlNodeList returned from SelectNodes after you manipulate the document might not be what you expect but is in line with the documentation. You will have to call SelectNodes again to get a new XmlNodeList if you manipulate the document.

In my view the designers of the DOM implementation in the .NET framework made a mistake by using XmlNodeList as an abstract class for concrete implementation with quite different behaviour. If you use e.g. ChildNodes then you get a "live" node list in line with what the W3C DOM specification requires so in that case a document change automatically changes the node list (if needed). However SelectNodes returns a node list with a quite different behaviour, as you experienced.

0

精彩评论

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