How to extracting the XML contents of an XDocument variable?
I have the a full XML file in an XDocument variable which I get from some API like this
using (var reader = XmlReader.Create("website"))
{
开发者_开发知识库 doc = XDocument.Load(reader);
}
I need to get the structure of the XML and navigate through its nodes, but through the XDocument variable, I only get the whole document in one node and can not extract each node by itself. So any solution or shall I use another way?
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx is a good article on building it up
you can also use linq to query it
for instance
var loaded = XDocument.Load("sdaf");
var q = from c in loaded.Descendants("contact")
where (int)c.Attribute("contactId") < 4
select (string)c.Element("firstName") + “ “ +
(string)c.Element("lastName");
taken off the page i linked to above.
The XDocument and XElement objects kick ass in my opinion. If you dont like them then go learn xpath and xslt.
To obtain the immediate child nodes of your XDocument
you can try
using (var reader = XmlReader.Create("website"))
{
var doc = XDocument.Load(reader);
var childElements = doc.Elements();
}
Then do further processing such as childElements.Descendants("name").Single().Value
.
string xml = reader.ReadToEnd();
XmlDocument thisXmlDoc = new XmlDocument();
thisXmlDoc.LoadXml(xml); // In your case DOC
reader.Close();
XPathNavigator thisNavigator = thisXmlDoc.CreateNavigator();
XPathNodeIterator dossierNodes = thisNavigator.Select("Nodename/node");
List<Dossier> thisList = GetDossiers(dossierNodes);
thisDossierList = thisList.OrderBy(c => c.something).ToList();
he is using XDocument objects, not XMLDocument objects. – John Nicholas 52 secs ago
Damn, you're right. Sorry! Only tried to help...
XmlDocument xdoc;
xdoc = new XmlDocument();
xdoc.Load(XmlReader.Create("weblink"));
The XDocument is not possible to be analyzed and extract its XML values which is possible in XmlDocument
精彩评论