I have an xml schema like below
<library>
<book>
<id>1</id>
<name>abc</name>
<read>
<data>yes</data>
<num>20</num>
</read>
</book>
<book>
<id>20</id>
<name>xyz</name>
<read>
<data>yes</data>
<num>32</num>
</read>
</book>
</library>
Now if the id
is 20
i need to take the value of tag <num>
under <read>
I done the code as below
var xmlStr = File.ReadAllText("e_test.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("book").Where(x => x.Element("id").Value.Equals("20")).ToList();
this give the whole <book>
tag with id 20
. From this how can I extract only the value of tag <num>
.
ie is i need to get the value 32
in to a variable
Before you try to extract the num
value, you need to fix your Where
clause - at the moment you're comparing a string with an integer. The simplest fix - if you know that your XML will always have an id
element which has a textual value which is an integer - is to cast the element to int
.
Next, I'd use SingleOrDefault
to make sure there's at most one such element, assuming that's what your XML document should have.
Then you just need to use Element
twice to navigate down via read
and then num
, and cast the result to int
again:
// Or use XDocument doc = ...; XElement book = doc.Root.Elements("book")...
XElement root = XElement.Load("e_test.xml")
XElement book = root.Elements("book")
.Where(x => (int) x.Element("id") == 20)
.SingleOrDefault();
if (book == null)
{
// No book with that ID
}
int num = (int) book.Element("read").Element("num");
See more on this question at Stackoverflow