I went through a lot of resources, did a lot of research, and tried a lot of “best guesses” to access one element at a time using WebMatrix with C # web pages, however none of what I'm trying to do is walk through.
Consider a simple XML document that looks like this:
<root> <requisitionData> <element1>I am element 1</element1> <element2>I am element 2</element2> </requisitionData> </root>
I know that I can use the foreach loop, for example:
@using System.Xml.Linq XDocument doc = XDocument.Load(Server.MapPath("~/User_Saves/cradebaugh/testFile.xml")); foreach (XElement element in doc.Descendants("requisitionData")) { @element.Value }
And that, of course, works great. But what if I just wanted to save a single element, <element1> value in a string variable?
I looked here (link below), but I can’t do the heads or tails of this code (it almost doesn't look like C # to me, but again, I'm so new to XML parsing ...):
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/b14ce4d1-77f1-420d-ad91-0989794a1d45/
I also checked here: How to get XML Node from XDocument
But the code above makes no sense to me. I keep thinking that there should be an easier way to do this, hopefully without exploring a completely new approach to the survey.
--------------------------------- THINGS I RECEIVED --------- --- ---------------------
XDocument doc = XDocument.Load(Server.MapPath("~/User_Saves/cradebaugh/testFile.xml")); string element = doc.Descendants("requisitionData").Descendants("element1").Value;
The error I get is: "missing using a directive or assembly reference
XDocument doc = XDocument.Load(Server.MapPath("~/User_Saves/cradebaugh/testFile.xml")); XElement element = doc.Descendants("element1"); string val = element.Value;
The error I get: It is not possible to implicitly convert the type 'System.Collections.Generic.IEnumerable' to 'System.Xml.Linq.XElement'. Explicit conversion exists (are you skipping listing?)
I really tried other things, but I get almost the same errors as shown above. Am I making it harder than this, or am I simplifying this?
------------------------- UPDATE --------------------- --- ------
I managed to get this to work:
string element = doc.Element("root").Element("requisitionData").Element("element1").Value; @element
However, one thing that concerns me in this approach is that .Element selects the "first" match, so it looks like this in an XML document:
<root> <requisitionData> <element1>I am element 1</element1> <element2>I am element 2</element2> </requisitionData> <requisitionData> <element1>I am element 1</element1> <element2>I am element 2</element2> </requisitionData> </root>
How do I access the second occurrence of <element1> ?