c#
  • linq-to-xml
  • xelement
  • 2012-01-16 85 views 1 likes 
    1

    我试图从XElement (使用.Remove())删除后代元素,我似乎得到一个空对象引用,我不知道为什么。根据属性值从XML中删除元素?

    说完看着前面的问题与这个称号see here,我找到了一种方法来删除它,但我仍然不明白为什么我第一次尝试没有工作的方式。

    有人能够启发我吗?

    String xml = "<things>" 
          + "<type t='a'>" 
          + "<thing id='100'/>" 
          + "<thing id='200'/>" 
          + "<thing id='300'/>" 
          + "</type>" 
          + "</things>"; 
    
        XElement bob = XElement.Parse(xml); 
    
        // this doesn't work... 
        var qry = from element in bob.Descendants() 
          where element.Attribute("id").Value == "200" 
          select element; 
        if (qry.Count() > 0) 
        qry.First().Remove(); 
    
        // ...but this does 
        bob.XPathSelectElement("//thing[@id = '200']").Remove(); 
    

    感谢, 罗斯

    回答

    2

    的问题是,你是迭代集合包含不具备id属性的一些元素。对他们来说,element.Attribute("id")null,所以试图访问Value属性会抛出NullReferenceException。要解决这个

    一种方法是使用a cast而不是Value

    var qry = from element in bob.Descendants() 
          where (string)element.Attribute("id") == "200" 
          select element; 
    

    如果一个元素没有id属性,剧组将返回null,在这里工作得很好。

    而且,如果您正在进行演员阵容,则可以将其转换为int?(如果需要)。

    +0

    谢谢svick,我明白了现在的问题。 – 2012-01-16 10:26:17

    1

    尝试以下操作:

    var qry = bob.Descendants() 
           .Where(el => el .Attribute("id") != null) 
           .Where(el => el .Attribute("id").Value = "200") 
    
        if (qry.Count() > 0) 
        qry.First().Remove(); 
    

    你需要获取其值之前测试的id属性的存在。

    +0

    感谢您的有用建议。检查属性 - 我明白了为什么它根据svick的回答有关。 – 2012-01-16 10:22:35

    +0

    @BlackLight哦,值得一试! – ColinE 2012-01-16 10:23:49

    +0

    那么,没有进攻,但它已经超过三年了,我真的很惊讶没有人看到这个代码中的任何错误。有3个非常明显的错误。 'el .Attribute'有两个空格和'Attribute(“id”)。值=“200”'应该是'Attribute(“id”)。Value ==“200”'。注意double =符号。 – 2015-02-14 16:44:30

    相关问题