XDocument通过其名称属性的值获取XML元素我有这样的XML结果016firstname16557Managersurname1firstname26203Directorsurname2我想得到一个对象列表,每个对象都包含ContaFirstname、ContaId、ContaJobTitle和ContaSurname我试过这样的东西,但那是不对的,因为我得到了它们vartest=fromcinxml.Descendants("doc")selectnew{firstname=c.Element("ContaFirstname"),surnmane=c.Element("ContaSurname")};那么如何按名称访问这些元素呢?您不想按名称访问元素,因为大多数人会解释该语句。您希望通过名称属性的值访问元素:firstname=(string)c.Elements("str").First(x=>x.Attribute("name").Value=="ContaFirstname");//etc你可能想把它抽象成一个单独的方法,因为多次这样做会很麻烦。例如:publicstaticXElementElementByNameAttribute(thisXContainercontainer,stringname){returncontainer.Elements("str").First(x=>x.Attribute("name").Value==name);然后:vartest=fromcinxml.Descendants("doc")selectnew{firstname=c.ElementByNameAttribute("ContaFirstname").Value,surfmane=c.ElementByNameAttribute("ContaSurname").Value};如果您有权访问您的文档提供更合理的结构,那将是更可取的...这是否解决了您的问题:vartest=fromcinxml.Descendants("doc")selectnew{firstname=c.Elements("str").First(element=>element.Attribute("name").Value=="ContaFirstname"),surfmane=c.Elements("str").First(element=>element.Attribute("name").Value=="ContaSurname")};或者,如果你想要的是值(而不是XElement:以上是C#学习教程:XDocument通过其name属性的值获取XML元素共享的全部内容,如果对大家有用还需要进一步了解C#希望大家多多关注教程—vartest=fromcinxml.Descendants("doc")selectnew{firstname=c.Elements("str").First(element=>element.Attribute("名称").Value=="ContaFirstname").Value,surnmane=c.Elements("str").First(element=>element.Attribute("name").Value=="ContaSurname").Value};本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
