Home > Software engineering >  XML/C# Cannot read read attribute of an element
XML/C# Cannot read read attribute of an element

Time:08-22

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.

CodePudding user response:

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

CodePudding user response:

I would use XML Linq and create a dictionary

using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApp2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Descendants().Where(x => x.Name.LocalName == "property")
                .GroupBy(x => (string)x.Attribute("name"), y => (string)y.Attribute("value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }

    }
   
}
  • Related