2

I have XElement object formated like this :

<Setting guid="3bcedf55-b75f-456b-b90a-a92cbbb022ga">
    <PatientFieldList>
        <PatientFieldSetting PatientName="UserDecision" PatentFieldLength="64" />
        <PatientFieldSetting PatientName="prohibited" PatentFieldLength="128" />
    </PatientFieldList>
</Setting>

I have to get values of all attributes in all nodes but I don't know how :/ I tried

xml.Elements("PatientFieldList")

xml.Descendants("PatientsSettingsFieldsList").Where(x => x.Attribute("PatentFieldLength").Value == 64)`

I have a lot of node like that so i wonder if there is easy way to access to these attribute by '[]' or somehow.

2 Answers 2

5

Code:

using System;
using System.Linq;
using System.Xml.Linq

var xml = "<Setting ...";
var doc = XElement.Parse(xml);
int i; // for int parse
var q = from node in doc.Descendants("PatientFieldSetting")
        let name = node.Attribute("PatientName")
        let length = node.Attribute("PatentFieldLength")
        select new { Name = (name != null) ? name.Value : "", Length = (length != null && Int32.TryParse(length.Value, out i)) ? i : 0 };

foreach (var node in q)
{
    Console.WriteLine("Name={0}, Length={1}", node.Name, node.Length);
}

Output:

Name=UserDecision, Length=64
Name=prohibited, Length=128
Sign up to request clarification or add additional context in comments.

Comments

1

This will print out attributes of all nodes which have attributes in your xml:

XDocument doc = //your data

var q = from node in doc.Descendants()
        where node.Attributes().Count() > 0
        select new {NodeName = node.Name, Attributes = node.Attributes()};

foreach (var node in q)
{
    Console.WriteLine( node.NodeName );
    foreach (var attribute in node.Attributes)
    {
        Console.WriteLine(attribute.Name + ":" + attribute.Value);
    }
    Console.WriteLine();
}

If you only want PatientFieldSetting nodes filter for the name:

from node in doc.Descendants("PatientFieldSetting")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.