无法使用XDocument

时间:2015-05-28 09:07:13

标签: vb.net linq-to-xml

我已获得customUIXml类型的XDocument对象,并且它具有以下XML作为值:

<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <ribbon>
    <tabs>
      <tab id="t1" label="Shalala">
        <!-- stuff -->
      </tab>
      <tab id="tab_dev" label="SomeOtherTab">
        <!-- stuff -->
      </tab>
      <tab id="t108" label="MyTab">
        <!-- stuff -->
      </tab>
    </tabs>
  </ribbon>
</customUI>

我希望获得标签值为#{1}的节点&#34; MyTab&#34;。这是我使用的代码:

tab

但我没有得到任何结果,我似乎无法找到我做错的事情......

2 个答案:

答案 0 :(得分:0)

您可以简单地使用XML文字,因此您的代码就像以下一样简单:

Dim xtab = customUIXml.<ribbon>.<tabs>.<tab>.First(Function(tab) tab.@label = "MyTab")

此外,您的代码似乎有效,因此您的问题似乎在其他地方。

Dim customUIXml = <customUI>
<ribbon>
    <tabs>
    <tab id="t1" label="Shalala">
        <!-- stuff -->
    </tab>
    <tab id="tab_dev" label="SomeOtherTab">
        <!-- stuff -->
    </tab>
    <tab id="t108" label="MyTab">
        <!-- stuff -->
    </tab>
    </tabs>
</ribbon>
</customUI>

Dim xtab As XElement = Nothing
Dim nodes = From nodeToTake In customUIXml.Descendants().Elements("tab") _
            Where nodeToTake.Attribute("label").Value = "MyTab"
            Select nodeToTake

For Each tab As XElement In nodes
    xtab = tab
Next

Console.WriteLine(xtab)

显示器

<tab id="t108" label="MyTab">
  <!-- stuff -->
</tab>

很好。

如果您的实际XML包含命名空间,则必须考虑到这一点:

...
Dim df As XNamespace = customUIXml.Name.Namespace

Dim xtab As XElement = Nothing
Dim nodes = From nodeToTake In customUIXml.Descendants().Elements(df + "tab") _
            ...

答案 1 :(得分:0)

string xml = "<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' onLoad='Ribbon_Load'><ribbon><tabs><tab id='t1' label='Shalala'><!-- stuff --></tab><tab id='tab_dev' label='SomeOtherTab'><!-- stuff --></tab><tab id='t108' label='MyTab'><!-- stuff --></tab></tabs></ribbon></customUI>";

var xelement = XElement.Parse(xml);
var list = xelement.Descendants().Where(x => x.Name.LocalName == "tab" && x.Attribute("label") != null).ToList();
list.ForEach(x => Console.WriteLine(x.Attribute("label").Value));

您可以访问localName来检查elment标记值, 与LinqPad一起检查,预计它有望帮助..

:)

编辑:Telerik转换的Vb代码:

Dim xml As String = "<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' onLoad='Ribbon_Load'><ribbon><tabs><tab id='t1' label='Shalala'><!-- stuff --></tab><tab id='tab_dev' label='SomeOtherTab'><!-- stuff --></tab><tab id='t108' label='MyTab'><!-- stuff --></tab></tabs></ribbon></customUI>"

Dim xelement__1 = XElement.Parse(xml)
Dim list = xelement__1.Descendants().Where(Function(x) x.Name.LocalName = "tab" AndAlso x.Attribute("label") IsNot Nothing).ToList()
list.ForEach(Function(x) Console.WriteLine(x.Attribute("label").Value))