不能比 root 更深入,LINQ to (Funds)XML,C#

Cant go deeper than root, LINQ to (Funds)XML, C#

我正在使用一个特定的基金XML-Schema 试图获取一个特定XML-文件的所有Assets来迭代。

xml-文件的简短示例:

<?xml version="1.0" encoding="utf-8"?>
<FundsXML xmlns="http://www.fundsxml.org/XMLSchema/3.0.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="3.0.5" xsi:schemaLocation="http://www.fundsxml.org/XMLSchema/3.0.5 FundsXML3.0.5.xsd">
<Date>2015-02-27</Date>
...
<AssetMasterData>
   <Asset>
      <SecurityCodes>
         <ISIN>XXXXXXXXXXXX</ISIN>
      </SecurityCodes>
   </Asset>
   ...
   <Asset>
</AssetMasterData>
</FundsXML>

我想遍历其中的 Assets。我试过了:

XDocument xmlTree = XDocument.Load(xmlPath);
XElement root = xmlTree.Root;
foreach (XElement f in root.Descendants())
        {
            System.Windows.MessageBox.Show(f.Name.ToString() +" ; "+f.Value.ToString());
        }

输出:{http://www.fundsxml.org/XMLSchema/3.0.5}日期; 2015-02-27

第二部分是读取每个 Asset 节点的 ISIN。 但是我没有时间这样做,因为我在第一部分就失败了。

编辑:

解决方案是搜索名称空间+名称:

foreach (XElement f in root.Descendants("{http://www.fundsxml.org/XMLSchema/3.0.5}Asset"))

我认为的最佳解决方案:

foreach (XElement f in root.Descendants(xmlTree.Root.GetDefaultNamespace()+"Asset"))

基于您提供的样本数据

<Asset></Asset>

里面似乎没有任何数据。您需要获得

foreach (XElement f in root.Descendants("ISIN"))

反正我觉得。如果没有实际文本,那么您将得到一个空白或空值??所以听起来它正在返回你所要求的东西??

由于您的 XML 在命名空间中,您需要将命名空间信息添加到后代查询中。

你可以看一个例子here

您可以尝试获取

roots.Descendants()

不过滤并检查它 returns 的节点以确认这一点。