簡體   English   中英

我正在嘗試在vb.net中使用xml linq xdocument

[英]i'm trying to work with xml linq xdocument in vb.net

我正在嘗試編寫Windows Phone 7應用程序,該應用程序使用xdocument從xml讀取,但是我遇到了一些問題。

如果我這樣做:

Dim xml As XDocument = XDocument.Load(e.Result)
System.Diagnostics.Debug.WriteLine(xml.ToString)

或這個:

System.Diagnostics.Debug.WriteLine(xml.Elements.Value.ToString)

然后將xml數據作為字符串輸出到imimiate窗口,證明該數據存在,但是如果我這樣做:

Dim products = From product In xml.Descendants("product") _
                    Select title = product.Element("title").Value

For Each product In products
     System.Diagnostics.Debug.WriteLine("Title" & product.title)
Next

我對product.title一無所獲,當我做這樣的事情時,我也一無所獲:

Dim count As Integer = xml.Descendants("count").Value

我究竟做錯了什么? 謝謝。

xml看起來像這樣:

<productslist>
  <count>2</count>
  <products>
    <product>
        <productId>1</productId>
        <title>test item 1 </title>
        <price>4.99</price>
        <category>
            <categoryId>1</categoryId>
            <categoryName>cat 1</categoryName>
        </category>
    </product>
    <product>
        <productId>2</productId>
        <title>test item 2</title>
        <price>10.99</price>
        <category>
            <categoryId>2</categoryId>
            <categoryName>cat 2</categoryName>
        </category>
    </product>
 </productslist>

您的LINQ語句未投影到具有Title屬性的匿名類型。 您將直接獲得IEnumerable<string>

嘗試以下方法:

Dim products = From product In xml.Descendants("product") _
               Select product.Element("title").Value

For Each product In products
     Debug.WriteLine("Title: " & product)
Next

就是說,變量products被更好地命名為titles 如果要投影為匿名類型,則需要使用With New { .Prop1 = data, .Prop2 = other } 每個屬性名稱前必須加一個點。 這是一個例子:

Dim products = From product In xml.Descendants("product") _
               Select New With { .Title = product.Element("title").Value }

For Each product In products
     Debug.WriteLine("Title: " & product.Title)
Next

對於您的示例,似乎不需要匿名類型。 如果您有多個要投影的屬性,那么它值得。

編輯:響應您的評論,名稱空間可能會附加到您的XML。 如果是這樣,則需要引用它以引用任何元素。

如果您的XML具有名稱空間,則應指定一個xmlns ,例如:

<productslist xmlns="http://domain.com/namespace">

然后,您將必須修改代碼以獲取名稱空間,並將其與元素連接起來,如下所示:

Dim ns = xml.Root.GetDefaultNamespace()

Dim products = From product In xml.Descendants(ns + "product") _
               Select product.Element(ns + "title").Value

抱歉,我不知道VB,但是在C#中,此代碼可以做到-

var query = doc.Descendants("product").Select(x => new {Title= x.Element("title").Value});

            foreach (var item in query)
            {
                Console.WriteLine(item.Title);

            }

另外,您發布的xml缺少</products> 節點(結束標簽),我希望這只是一個復制粘貼錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM