0
我的XML獲取嵌套元素的LINQ to XML
<?xml version="1.0" encoding="utf-8"?>
<metadata created="2014-05-15T12:26:07.701Z" xmlns="http://site/cu-2.0#" xmlns:ext="http://site/cu/b-2.0">
<customer-list count="47" offset="0">
<customer id="7123456" type="Cust" ext:mark="1">
<name>Tony Watt</name>
<sort-name>Watt, Tony</sort-name>
<gender>male</gender>
<country>US</country>
<knownAs-list>
<knownAs locale="ko" sort-name="Tony Watt"</knownAs>
<knownAs locale="ja" sort-name="Watt Tony"</knownAs>
</knownAs-list>
<tag-list>
<begin>Country</begin>
<tag count="1">
<name>usa</name>
</tag-list>
</customer>
<customer id="9876543" type="Cust" ext:mark="2">
....
</customer-list>
所以我有一些代碼,獲取的所有數據。我進了一步使用匿名類型和添加的值成一個類,如下
Dim c = From cust As XElement In XDoc.Descendants(ns + "customer")
Select New Customer() With {.Name = cust.Element(ns + "name"),
.Surname = CStr(cust.Element(ns + "surname")),
.Id = cust.Attribute("id"),
.Tag = CStr(cust.Element("tag-list").Element("begin"))}
以上代碼從XML返回數據,但添加這行代碼
.Tag = CStr(cust.Element("tag-list").Element("begin"))
拋出異常, 「你調用的對象是空的」。現在那裏有此兩種可能性
- 我有我的代碼錯誤的特定行(從「標記列表」元素檢索「開始」)
- 我知道有些標籤列表元素沒有一個嵌套開始因此可能會增加一些混淆。我補充Cstr來克服這一點,但不知道這是否足夠?
閱讀MSDN似乎使用.Descendants(Xdoc.Descendants)將得到其中的元素將返回數據高達我已經指出了路徑中的所有元素中的所有數據,所以據我可以告訴數據「後應該與上面的代碼一起提供。任何人都可以幫助我從標籤列表中獲取開始數據嗎?
您確定標籤元素有效嗎?我看不到結束標記 – dotnetom
對不起,我注意到我沒有正確添加/格式化XML,我現在已經改變了 – Computer
你可能想考慮使用XPath:http://stackoverflow.com/questions/3642829/ how-to-use-xpath-with-xelement-or-linq – Neolisk