如何在VB.NET中使用LINQ从XML检索数据?

时间:2018-11-23 19:18:52

标签: vb.net linq

我找不到使用LINQ从XML文件获取值的方法。

代码如下:

Dim XMLDoc As XDocument = XDocument.Load(XMLPath)

Dim query = From ex In XMLDoc.Descendants.Elements("DSServer")
                Select New With
                    {
                    .svrname = ex.Element("ServerName"),
                    .BG = ex.Element("IsBG")
                    }

For Each t In query
    MsgBox(t.svrname.Value.ToString + " " + t.BG.Value.ToString)
Next

这是XML

<?xml version="1.0" standalone="yes"?>
<DSPaths xmlns="http://tempuri.org/DSPaths.xsd">
  <DSServer>
    <ServerName>test1Name</ServerName>
    <ServerIP>test1</ServerIP>
    <ServerPath>test1</ServerPath>
    <Destination>test1</Destination>
    <IsBG>true</IsBG>
  </DSServer>
  <DSServer>
    <ServerName>test2Name</ServerName>
    <ServerIP>test2</ServerIP>
    <ServerPath>test2</ServerPath>
    <Destination>test2</Destination>
    <IsBG>true</IsBG>
  </DSServer>
</DSPaths>

我在做什么错了?

代码不返回任何内容...

1 个答案:

答案 0 :(得分:1)

如果无法从xml中删除名称空间,则需要在查询中指定名称空间。

    Dim ns As XNamespace = "http://tempuri.org/DSPaths.xsd"

    Dim query = From ex In XMLDoc.Descendants.Elements(ns + "DSServer")
                Select New With
                {
                .svrname = ex.Element(ns + "ServerName"),
                .BG = ex.Element(ns + "IsBG")
                }