user565992
user565992

Reputation: 497

Xdocument parse file and read values

I have the below sample XML , I need to retrive the values for the following two fields txJu and ddate.I also have the code but it is giving null expection

<Doc id="580171" ddate="2019-06-21" >                       
    <ref dtRef="2019-08-21">                    
        <dr>                
            <cr>            
                <pj>        
                    <pr>    
                        <dDup txJu="0.00" txFi="0.00" txcOp="0.00" />
                        <comp txJu="12.96" txFi="2.45" txOp="0.00" />
                    </pr>   
                </pj>       
            </cr>           
        </dr>               
    </ref>                  
</Doc>  





  var xdoc = XDocument.Load(file);
   string txJu = xdoc.Root.Element("comp").Attribute("txJu").Value;
   string ddate = xdoc.Root.Element("Doc").Attribute("ddate").Value;  

Upvotes: 0

Views: 164

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23258

There are a couple of issues with your code. Your Root element doesn't contain comp node, Doc element is root itself, string ddate = string value = ... is invalid C# declaration. You can modify your code per following

var compElement = xdoc.Root?.DescendantsAndSelf("comp").FirstOrDefault();
string txJu = compElement?.Attribute("txJu")?.Value;
string ddate = xdoc.Root?.Attribute("ddate")?.Value;
string value = ddate;

Use DescendantsAndSelf method to get a collection of filtered comp elements and use first of them. Access ddate attribute directly in Root element. Use null-conditional operator ? to avoid possible null reference exceptions

Upvotes: 1

Related Questions