這種方法實在是不完整的,不愧爲C#和一些解釋初學者LINQ到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只是一個小:該(string)
投上t
作用於發動機罩下的t.Value
<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
。如果不投,結果是:
<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();
您可以搜索任何element或的IEnumerable
味道descendant。
你嘗試過什麼嗎? – czuroski
顯示你已經嘗試過的東西,關於在C#中解析XML有很多。 –
我會欺騙,在內存中創建一個System.Data.DataTable對象,使用DataTable.ReadXML函數,並將它放在一個方便的DataTable中使用。但這是一種黑客攻擊,如果我將其作爲真正的答案,我可能會被槍殺。 – David