【问题标题】:LINQ to XML - why is Elements always nullLINQ to XML - 为什么元素总是为空
【发布时间】:2012-08-09 18:03:15
【问题描述】:

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

【问题讨论】:

  • 你里面有命名空间吗?
  • 感谢您的回答 - 我的问题是,当我多年前使用 Xpath 时,我可以在不知道 ns 的情况下获得一个节点,您是否总是需要知道命名空间使用 LINQ to XML 获取元素?
  • 有可能。看这里:stackoverflow.com/questions/1145659/…
  • @Truegilly,请检查编辑后的答案。

标签: c# linq-to-xml


【解决方案1】:

定义 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");

【讨论】:

    【解决方案2】:

    您需要包含您的命名空间。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多