Search code examples
c#xmlxpathlinq-to-xmlxmlreader

XML/C# Cannot read read attribute of an element


I have this xml:

<root>
  <property name="com.jaspersoft.studio.js.ic.path" value="/InputControls/pEnforcementStatusID" xmlns="http://jasperreports.sourceforge.net/jasperreports" />
  <property name="com.jaspersoft.studio.js.ic.label" value="Enforcement Status ID" xmlns="http://jasperreports.sourceforge.net/jasperreports" />
  <defaultValueExpression xmlns="http://jasperreports.sourceforge.net/jasperreports"><![CDATA[0]]></defaultValueExpression>
</root>

I need to extract the "properties list with name & value", like this:

  1. name="com.jaspersoft.studio.js.ic.path" with value "/InputControls/pEnforcementStatusID"
  2. name="com.jaspersoft.studio.js.ic.label" with value "Enforcement Status ID"

I try to do that using xpath, xmlreader, linq to xml without success.


Solution

  • Works with XPath, then enumerate to get the property value.

    using System.Xml;
    using System.Xml.Linq;
    
    foreach (var current in doc.DocumentElement.SelectNodes("//root//*[local-name()='property']"))
    {
        Console.WriteLine($"Name: {current.Attributes["name"].Value}, Value: {current.Attributes["value"].Value}");
    }
    

    Demo @ .NET Fiddle