Luk*_*kas 306
这很简单.我知道这些是标准方法,但您可以创建自己的库来更好地处理.
这里有些例子:
XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file
// Get elements
XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge");
XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");
// Display the results
Console.WriteLine("Address: " + girlAddress[0].InnerText);
Console.WriteLine("Age: " + girlAge[0].InnerText);
Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);
Run Code Online (Sandbox Code Playgroud)
此外,还有一些其他方法可以使用.例如,这里.我认为没有一种最好的方法可以做到这一点; 你总是需要自己选择,最适合你的是什么.
Dav*_*itt 47
使用一个好的XSD Schema用xsd.exe创建一组类,并使用XmlSerializera从XML创建一个对象树,反之亦然.如果您对模型的限制很少,您甚至可以尝试使用Xml*Attributes在模型类和XML之间创建直接映射.
有一篇关于 MSDN上的XML序列化的介绍性文章.
性能提示:构建一个XmlSerializer很昂贵的.XmlSerializer如果要打算/编写多个XML文件,请保留对实例的引用.
Vin*_*vic 18
使用XmlTextReader,XmlReader,XmlNodeReader和System.Xml.XPath命名空间.和(XPathNavigator,XPathDocument,XPathExpression,XPathnodeIterator).
通常XPath使阅读XML变得更容易,这正是您可能正在寻找的.
我刚刚被要求处理一个涉及解析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");
}
Run Code Online (Sandbox Code Playgroud)
通过这些函数,我能够解析XML文件中的任何元素和任何属性都没有问题!
在Addition中,您可以通过以下方式使用XPath选择器(选择特定节点的简便方法):
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);
Run Code Online (Sandbox Code Playgroud)
我不确定是否存在"解析XML的最佳实践".有许多适合不同情况的技术.使用哪种方式取决于具体情况.
你可以去的LINQ to XML,XmlReader,XPathNavigator或者甚至正则表达式.如果你详细说明了你的需求,我可以尝试提出一些建议.
| 归档时间: |
|
| 查看次数: |
393642 次 |
| 最近记录: |