XML字符串到XML文档 [英] XML string to XML document
本文介绍了XML字符串到XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在字符串,我需要转换为XML文档并解析标签文档中的整个XML文档
解决方案
此代码示例是从 csharp-examples.net 一取>,以一月Slama书面的:
要找到可以使用XPath表达式的XML文件的节点。方法XmlNode.SelectNodes返回由XPath字符串选择的节点列表。 。方法XmlNode.SelectSingleNode认定的XPath字符串匹配的第一个节点。
块引用>
XML:
<家具名字GT;
<名称>
<&名字GT;约翰和LT; /姓>
<&姓氏GT;史密斯和LT; /姓氏>
< /名称>
<名称>
<&名字GT;詹姆斯< /姓>
<&姓氏GT;白色< /姓氏>
< /名称>
< /姓名与GT;
块引用>
代码:
XmlDocument的XML =新的XmlDocument();
xml.LoadXml(myXmlString); //假设myXmlString包含<家具名字GT; ...< /姓名与GT;
XmlNodeList中xnList = xml.SelectNodes(/姓名/名称);
的foreach(在xnList XmlNode的XN)
{
串的firstName = XN [名字]的InnerText。
字符串的lastName = XN [姓氏]的InnerText。
Console.WriteLine(名称:{0} {1},名字,姓氏);
}
块引用>I have a whole XML document in a String which i need to convert to a XML document and parse tags in the document
解决方案This code sample is taken from csharp-examples.net, written by Jan Slama:
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
XML:
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
CODE:
XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>" XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }
这篇关于XML字符串到XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文