Search code examples
c#linq-to-xmlxelement

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


I'm working with a specific FundsXML-Schema trying to get all Assetss of a specific XML-File to iterate through.

Short example of xml-file:

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

I want to iterate through Assets in there. I tried:

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());
        }

Output: {http://www.fundsxml.org/XMLSchema/3.0.5}Date ; 2015-02-27

The second part would be to read ISIN of each Asset node. But I hadn't time to do this, because I'm failing at the first part.

EDIT:

Solution was to search for namespace+name:

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

Best solution in my opinion:

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

Solution

  • As your XML is in a namespace, you need to add the namespace information to the Descendants query.

    You can see an example here

    You can try to get the

    roots.Descendants()
    

    Without filtering and check the nodes that it returns to confirm this.