XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'
// Retrieve your data here or change XML here:
foreach (XmlNode book in nodeList)
{
book.InnerText="The story began as it was...";
}
Console.WriteLine("Display XML:");
doc.Save(Console.Out);
我最近被要求处理一个涉及XML文档解析的应用程序,我同意Jon Galloway的观点,基于LINQ to XML的方法在我看来是最好的。然而,我不得不挖掘一些有用的例子,所以闲话少说,这里有一些!
欢迎任何评论,因为这段代码可以工作,但可能不是完美的,我想了解更多关于这个项目的XML解析!
public void ParseXML(string filePath)
{
// create document instance using XML file path
XDocument doc = XDocument.Load(filePath);
// get the namespace to that within of the XML (xmlns="...")
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
// obtain a list of elements with specific tag
IEnumerable<XElement> elements = from c in doc.Descendants(ns + "exampleTagName") select c;
// obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc
XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();
// obtain an element from within an element, same as from doc
XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();
// obtain an attribute from an element
XAttribute attribute = element.Attribute("exampleAttributeName");
}