1

im having trouble getting elements from my XML. I cannot get the Vehicles or Vehicle elements from my XML, it always returns null.

Can any one see where im going wrong?

Here is my code...

    [TestMethod]
    public void TestDeleteVehicleFromXMLFile()
    {
        using (FileStream stream = new FileStream(base._TestXPathXMLFile, FileMode.Open))
        {
            try
            {
                XDocument xDoc = XDocument.Load(stream);
                var q = from RootNode in xDoc.Descendants("VehicleCache")

                    select new
                    {
                        // Vehicles & VehiclesList is always null
                        Vehicles = RootNode.Elements(XName.Get("Vehicle")).ToList(),
                        VehiclesList = RootNode.Elements(XName.Get("Vehicles")).ToList(),
                        SelfNode = RootNode.DescendantNodesAndSelf().ToList(),
                        DescendantNodes = RootNode.DescendantNodes().ToList()
                    };

                // used to see what is in item
                foreach (var item in q)
                {
                    int i = 0;
                }
            }
            catch(Exception E)
            {
                Assert.Fail(E.Message);
            }
        }
    }


<VehicleCache>
<Vehicles xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.myURL.co.uk">
    <Vehicle>
      <CapCode>41653</CapCode>
      <TrueCap i:nil="true" />
      <VehicleID>365789</VehicleID>
      <ViperVehicleID i:nil="true" />
      <BodyTypeID>5</BodyTypeID>
    </Vehicle>
    <Vehicle>
      <CapCode>42565</CapCode>
      <TrueCap i:nil="true" />
      <VehicleID>365845</VehicleID>
      <ViperVehicleID i:nil="true" />
      <BodyTypeID>2</BodyTypeID>
    </Vehicle>
</Vehicles>

JGilmartin
  • 8,683
  • 14
  • 66
  • 85

2 Answers2

10

Define XNamespace

XNamespace ns = "http://www.myURL.co.uk";

Use that:

Vehicles = RootNode.Elements(XName.Get(ns + "Vehicle")).ToList(),

Or if you want to avoid using Namespace then try:

var result = xDoc.Descendants().Where(r => r.Name.LocalName == "VehicleCache");
ABH
  • 3,391
  • 23
  • 26
3

you need to include your namespace.

XNamespace Snmp = "http://www.myURL.co.uk";

for root descendants also you need to include namespace.

var q = from RootNode in xDoc.Descendants(Snmp +"VehicleCache")

like this

Vehicles = RootNode.Elements(XName.Get(Snmp + "Vehicle")).ToList()//snmp is the namespace
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83