c# - LINQ to XML - 为什么 Elements 总是 null

标签 c# linq-to-xml

我无法从我的 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");

关于c# - LINQ to XML - 为什么 Elements 总是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11880657/

相关文章:

c# - 反序列化使用 TypeNameHandling.All 序列化的字符串

c# - 针对多个模式验证未知 xml,直到找到匹配项

c# - 从 XDocument 获取 XmlElement

c# - 更有效地过滤 XDocument

c# - 集合被修改;枚举操作可能无法执行

c# - 错误 CS0246 : The type or namespace name 'StreamingContext' could not be found (are you missing a using directive or an assembly reference?)

c# - 通过c#解析xml时获取 "\/"等

c# - 从 XNode 检索属性值

c# - 嵌套锁对同一对象的性能

c# - WebAPI - 路由