Search code examples
c#xmllinqparsingxelement

Cannot access to a specific block of XML file with Linq


I am trying to get a specific block of a XML, I am using function load to take all my XML file and it works fine. When I am debugging i can see all the file. The problem is about when I am trying to get a specific value of xml.

I am using XElement of LINQ library. So, here is an example of my xml file:

-<Mission xmlns:z="http:..." xmlns:i="http:..." xmlns="http:..." z:Id="1">
    +<ActiveBullsEye z:Id="2" i:type="BullsEye">
    -<ActiveFlightPlan z:Id="7" i:type="FlightPlan">
        <AIRTAC z:Id="8"/>
        <Active>false</Active>
       -<Aircraft z:Id="9" i:type="a:Tanker" xmlns:a="http:...">
       -<ACColor xmlns:b="http:...">
             <b:A>255</b:A>
             <b:B>169</b:B>
             <b:G>169</b:G>
             <b:R>169</b:R>
             <b:ScA>1</b:ScA>
             <b:ScB>0.396755248</b:ScB>
             <b:ScG>0.396755248</b:ScG>
             <b:ScR>0.396755248</b:ScR>

I need to access block (ACColor) and then do a for statement to get all of these values. But I am trying something like this and not function for me:

XElement xdocument = XElement.load(filepath) //This works
XElement missionBlock = xdocument.Element("Mission") //(ERROR) This not get Mission tag

foreach( XElement acColor in missionBlock.Elements("ACColor") ) { // (ERROR) Not found ACColor
    ...
}

Could you help me to access to all values of ACColor node?


Solution

  • XElement xDocument = XElement.load(filepath);  // This works
    var ns = xDocument.GetDefaultNamespace();
    
          in missionBlock
                .Elements(ns + "ActiveBullsEye")    
    

    and to get at for instance the value of z:Id :

    var z = xml.GetNamespaceOfPrefix("z");
    var id = (string)xElement.Attribute(z + "Id");
    

    Do not use var when you create a namespace from a string:

    var ns1 = "http://something";         // ns1 is a string
    XNamespace ns2 = "http://something";  // ns2 is a namespace
    

    And you really need a namespace z for z + "Id" to work.