XML Node Access
I'm not sure what I am missing here.. I have an XML file which has several nodes.. in particular I am trying to get the LocalName of the node which is descendant of "Requirement". I've tried every combination I can think of and can't get it to let me access the node. When I check for if Requirement has elements, I get true... when I check to see if it has descendents - I get false.
Here is the XML
<Requirement type="Level"><gt>11</gt></Requirement>
Edit @ Jon - My question is how do I access the "GT" node? (It can change to be other items, so I do not want to reference it directly).
Here is my code so far:
public override void LoadXml(XElement element)
{
Value = element.Value;
EquateType = element.LastNode.Parent.Name.LocalName;
}
EquateType is the field I am trying to modify... LastNode actually returns an error, but as I said above I was navigating in the Immediate window and cannot seem to find the path that I开发者_如何学C need. Thanks in advance!
Or you can use XPAth..
EDIT:
XmlNode node= doc.SelectSingleNode("/Requirement//*"); //returns first occurence
string name = node.Name; //tada!
XmlNodeList list = doc.SelectNodes("/Requirement//gt");
//selects a
occuring anywhere within Requirement
.
EDIT2: To convert from XELement
to XmlNode
you can..
Step1: Create an XmlReader
using the CreateReader()
method.
Step2: Then load an XmlDocument
back using the XmlReader
returned from CreateReader()
.
Step3: Return the XmlDocument
as XMlNode
since XmlDocument
inherits XmlNode
. :)
Your code should like something below..
public static XmlNode GetXmlNode(this XElement element)
{
using (XmlReader xmlReader = element.CreateReader())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
return xmlDoc;
}
}
try this
var items = doc.Descendants("Requirement")
.Where(node => (string)node.Name == "gt")
.Select(node => node.Value.ToString())
.ToList();
If you're using an XDocument
, the first element in the document that's under a Requirement
element is:
XElement e = d.Descendants("Requirement").Elements().First();
and you can access its LocalName
property to get its local name. (Note the use of Elements
, which returns immediate child elements, rather than Descendants
, which returns all descendant elements. It doesn't matter in this case, since the first child element and the first descendant element are the same thing, but indiscriminately using Descendants
when you're only looking for child elements can get you into trouble.)
If you want to use XPath, you can:
XElement e = d.XPathSelectElement("//Requirement/*");
a huge thanks for everyone and their help. I ended up being able to get this to work using Linq.
EquateType = element.Elements().First().Name.LocalName;
精彩评论