Share via

XDocument parsing

Noah Aas 1,210 Reputation points
2024-04-16T14:25:16.3666667+00:00

Hello!

I have an XML document and I don't know how many more sub-elements there are. From Element SCANNER

How can I read this out intelligently?

<ROOT>
<PROGRAM>
    <NAME value="R5E9"/>
    <PRODUCT value="test"/>
    <PROGRAMMODES>
        <SCANNER text="Scan without stop" value="5">
            <DEVICE value="Scanner 1, SCANNER_1" text="Device"/>
            <ERRORHANDLING value="1" text="Errorhandling"/>
            <SEGMENT value="1" text="Segment"/>
//                further elements possible
        </SCANNER>
        <CAMERA text="Scanpanel" value="20">

My attempts

string currentProgram = material + "R5E9" + ".PROGRAM";
XDocument xDocProgram = XDocument.Load(currentProgram);
XElement elScanner = xDocProgram.XPathSelectElements("//PROGRAMMODES//SCANNER").FirstOrDefault();

if (elScanner != null)
{
	string text = elScanner?.Attribute("text").Value;
	string value = elScanner?.Attribute("value").Value;
	string errorhandling = elScanner?.Element("ERRORHANDLING").Attribute("value").Value;
}
else
{

}
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

  1. Viorel 126.9K Reputation points
    2024-04-16T17:21:42.71+00:00

    For example:

    var elements = elScanner.XPathSelectElements( "*[@text][@value]" );
    foreach( XElement element in elements )
    {
        string name = element.Name.LocalName;
        string text = element.Attribute( "text" ).Value;
        string value = element.Attribute( "value" ).Value;
    
        Console.WriteLine( "Element: {0}, Text: {1}, Value: {2}", name, text, value );
    }
    

    Was this answer helpful?

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.