简体   繁体   English

用linq(C#)读取xml

[英]reading xml with linq (c#)

how do I read the following xml document? 我如何阅读以下xml文档?

My code is : 我的代码是:

var vb =
    (from vbs in XMLDoc.Descendants("Response").Descendants("Records ")
    select new
        {
           ref = vbs.Element("ref").Value
        }).ToList();

XML Document: XML文件:

<Response>
  <Msg>
       <Code>30</Code>
    <Query/>
  </Msg>
<Rec>
    <Records price="1989" no="838976" ref="1927A64FF6B03527E5BFD8424F647848005143DB" query="00"/>
</Rec>
</Response>

"Records " should be "Records" , and your call to Element() in the anonymous class member initializer should be Attribute() since you are reading an attribute, which is not an element. "Records "应该是"Records" ,并且您在匿名类成员初始化器中对Element()调用应该是Attribute()因为您正在读取不是元素的属性。

var vb =
    (from vbs in XMLDoc.Descendants("Response").Descendants("Records")
    select new
        {
           ref = (string)vbs.Attribute("ref")
        }).ToList();

The conversion to string is preferred when reading attributes, IMO, because it will return null when the attribute cannot be found. 在读取属性IMO时,最好转换为string ,因为在找不到属性时它将返回null If you use vbs.Attribute("ref").Value instead, then you will cause a NullReferenceException if the attribute does not exist. 如果改用vbs.Attribute("ref").Value ,则如果该属性不存在,则会导致NullReferenceException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM