此方法确实不完整,值得为 C# 和 LINQ-to-XML 初学者做一些解释:
var types = XDocument.Load("http://simon.ist.rit.edu:8080/Services/resources/ESD/OrgTypes/")
.Descendants("type")
.Select(t => (string)t) // under the hood magic
.ToList();
使用(string) 进行投射有点神奇,如果使用ToString(),则不会得到相同的结果。我来解释一下……我只是稍微修改了 XML:
<type attrib="bar" attrib2="boo" >Resource
<foo a="1" a.2="A"/>
</type>
// note, I also removed the value of type immediately following Resource node
t 上的 (string) 在幕后作用于 t.Value。没有演员表,结果是:
<type>Physician</type>
<type>Ambulance</type>
<type>Fire Department</type>
<type>Helicopter/Air Transport</type>
<type>Home Care Agency</type>
<type>Hospital</type>
<type>Law Enforcement Agency</type>
<type>Nursing Home</type>
<type attrib="bar" attrib2="boo">Resource
<foo a="1" a.2="A" /></type>
<type></type>
<type>Other</type>
<type>Hospice</type>
<type>School</type>
<type>Emergency Shelter</type>
使用(string)t:
Physician
Ambulance
Fire Department
Helicopter/Air Transport
Home Care Agency
Hospital
Law Enforcement Agency
Nursing Home
Resource
Other
Hospice
School
Emergency Shelter
还有t.Value:
Physician
Ambulance
Fire Department
Helicopter/Air Transport
Home Care Agency
Hospital
Law Enforcement Agency
Nursing Home
Resource
Other
Hospice
School
Emergency Shelter
最后,要表明 t.ToString() 与 (string)t 不同:
<type>Physician</type>
<type>Ambulance</type>
<type>Fire Department</type>
<type>Helicopter/Air Transport</type>
<type>Home Care Agency</type>
<type>Hospital</type>
<type>Law Enforcement Agency</type>
<type>Nursing Home</type>
<type attrib="bar" attrib2="boo">Resource
<foo a="1" a.2="A" /></type>
<type></type>
<type>Other</type>
<type>Hospice</type>
<type>School</type>
<type>Emergency Shelter</type>
所有这些都是为了重申一些鲜为人知的问题 LINQ-to-XML。
为了清晰和易于维护,我的建议如下:
var types = XDocument.Load("http://simon.ist.rit.edu:8080/Services/resources/ESD/OrgTypes/")
.Descendants("type")
.Select(t => t.Value) // be explicit about what you want
.ToList();
您可以搜索IEnumerable 风格的任何element 或descendant。