繁体   English   中英

LINQ to XML-为什么Elements始终为null

[英]LINQ to XML - why is Elements always null

我在从XML中获取元素时遇到麻烦。 我无法从XML中获取Vehicles或Vehicle元素,它始终返回null。

谁能看到我在哪里出问题了?

这是我的代码...

    [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>

定义XNamespace

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

使用:

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

或者,如果您想避免使用命名空间,请尝试:

var result = xDoc.Descendants().Where(r => r.Name.LocalName == "VehicleCache");

您需要包括您的名称空间。

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

对于根后代,还需要包括名称空间。

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

像这样

Vehicles = RootNode.Elements(XName.Get(Snmp + "Vehicle")).ToList()//snmp is the namespace

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM