0

I cannot find a way to get the values from an XML file using LINQ.

Here is the code:

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

And here is the 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>

What am I doing wrong?

The code does not return anything...

3
  • 2
    I would assume that XMLDoc.Descendants.Elements("DSServer") doesn't return any value. So the problem should be before any LINQ. Have you tried removing (in the xml) or specifying (in the code) the namespace? Commented Nov 23, 2018 at 19:24
  • How can i do to specify the namespace? I tried removing the namespace in the XML file and it now works... but the thing is that my code writes the using an XSD file, so it enters the namespace in the XML. Commented Nov 23, 2018 at 19:28
  • I tried adding the following: Imports <xmlns="tempuri.org/DSPaths.xsd"> but the code returns nothing (I did put back the namespace in the XML) Commented Nov 23, 2018 at 19:38

1 Answer 1

1

If you can't remove the namespace from the xml, you'll need to specify the namespace in the query.

    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")
                }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.