How to get attribute in the XDocument object
Asked Answered
T

3

31

I have this xml

<config>
    <audio first="true" second="false" third="true" />
</config>

I want my code to able to do something like this

if (xdoc.getAttr("first")=="true")
    Console.Write("first is true");

How do I do this with LINQ XDocument? What I have so far is the XDocument Object loaded with that xml string.

Thorrlow answered 13/12, 2010 at 14:39 Comment(2)
I would answer, but it would be redundant. The operations you want to perform are in XElement.Carlsbad
@Slaks, i did, but i could not find what i am looking for, @legatou i ll have a look at XElement.Thorrlow
C
74

You need to get the attribute of the <audio> element:

string value = xdoc.Root.Element("audio").Attribute("first").Value;
Contagious answered 13/12, 2010 at 14:44 Comment(1)
this one is nice. I added Convert.toBoolean(value); to convert it to booleanThorrlow
G
2

You should take a look at XElement

article at c-sharpcorner.com

Gradin answered 13/12, 2010 at 14:44 Comment(0)
M
0

For my sample with the XDocument content :

<Dashboard>
  <Title Text="Test 1" />
  <DataSources>
     <JsonDataSource Name="JSON Data Source"/>
  </DataSources>

I use :

string name = xmlDashboard.Root.Element("Title").Attribute("Text").Value;
Memphian answered 31/5, 2024 at 15:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.