2011-12-29 43 views
5

cách xóa thuộc tính khỏi đối tượng System.Xml.XmlNode trong C#. Mã tôi đã thử không hoạt động. Nó ném một ngoại lệ "nút cần xóa không phải là nút con hợp lệ"Xóa thuộc tính khỏi XmlNode

foreach (XmlNode distribution 
     in responseXml.SelectNodes("/Distributions/Distribution/DistributionID")) 
{ 
    XmlAttribute attribute = null; 
    foreach (XmlAttribute attri in distribution.Attributes) 
    { 
    if (attri.Name == "GrossRevenue") 
     attribute = attri; 
    } 
    if (attribute != null) 
    distribution.ParentNode.RemoveChild(attribute); 
} 
+2

Bạn nên bao gồm dữ liệu xml để ai đó muốn thử mã của bạn có thể làm như vậy. –

Trả lời

8

XmlAttributes không phải là XmlNodes. XmlNode.ChildNodes thuộc loại XmlNodeList, trong khi XmlNode.Attributes thuộc loại XmlAttributesCollection. Để xóa thuộc tính, bạn sử dụng phương thức XmlAttributesCollection.Remove hoặc .RemoveAt. Trong mã của bạn:

distribution.ParentNode.Attributes.Remove(attribute); 
Các vấn đề liên quan