catalin87
catalin87

Reputation: 623

How to read this XML in C#?

I have this XML file. There is only one row. I need to read the file from its path and add the information to separate strings (dateJoined, totals, partials, status and counter).

For the moment I read the XML file like this:

var xml = System.Xml.Linq.XDocument.Load(@pathXML);

I am very noob at C# but I need to solve this problem.

XML file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
<DATAPACKET Version="2.0">
    <METADATA>
            <FIELDS>
                <FIELD attrname="dateJoined" fieldtype="dateTime"/>
                <FIELD attrname="totals" fieldtype="r8"/>
                <FIELD attrname="partials" fieldtype="r8"/>
                <FIELD attrname="status" fieldtype="r8"/>
                <FIELD attrname="counter" fieldtype="r8"/>
            </FIELDS>
        <PARAMS/>
    </METADATA>
    
    <ROWDATA>
        <ROW dateJoined="20201027" totals="41314.91" partials="134.55" status="2" counter="126"/>
    </ROWDATA>
</DATAPACKET>

How can I get all the attributes of the row in separate variables?

Upvotes: 2

Views: 778

Answers (2)

William Walseth
William Walseth

Reputation: 2923

As an alternative that's a little more flexible, use XPath.

XmlDocument xml = new XmlDocument();
xml.Load( @yourxmlfilenamepathhere);
XmlElement field = (XmlElement)xml.SelectSingleNode( "//ROWDATA/ROW" );

The rest of the code is the same.

The benefit, is that it won't break on most XML structure changes, and the XPath approach is simpler, especially if your looking way down deep in nested XML.

Upvotes: 1

marc_s
marc_s

Reputation: 754220

You could do something like this: get the <ROWDATA> node, then its first (and only) descendant, and from that node, extract the info from the attributes with this code:

var field = xml.Root.Descendants("ROWDATA").Descendants().FirstOrDefault();

if (field != null)
{
    string dateJoined = field.Attribute("dateJoined").Value;
    decimal total = decimal.Parse(field.Attribute("totals").Value);
    decimal partials = decimal.Parse(field.Attribute("partials").Value);

    int status = int.Parse(field.Attribute("status").Value);
    int counter = int.Parse(field.Attribute("counter").Value);
}

UPDATE: as @KlausGütter has noted in comments - if your .NET culture you're using uses something other than a dot (.) as its decimal separator, then this code won't properly convert the strings representing the decimal values.

To check what the decimal separator is, use this:

CultureInfo.CurrentCulture.Number.CurrencyDecimalSeparator

To properly convert the XML data to decimal in such a case, use:

    decimal total = (decimal)field.Attribute("totals");
    decimal partials = (decimal)field.Attribute("partials");

Upvotes: 3

Related Questions