将XMLstring转换为XML文档
我有一个string中的整个XML文档,我需要将其转换为XML文档并parsing文档中的标签
此代码示例取自Jan Slama编写的csharp-examples.net :
要查找XML文件中的节点,可以使用XPathexpression式。 方法XmlNode.SelectNodes返回由XPathstringselect的节点列表。 方法XmlNode.SelectSingleNode查找与XPathstring匹配的第一个节点。
XML:
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
码:
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); }
使用Linq到XML
添加对System.Xml.Linq的引用
并使用
XDocument.Parse(string xmlString)
编辑: 示例如下,xml数据(TestConfig.xml)..
<?xml version="1.0"?> <Tests> <Test TestId="0001" TestType="CMD"> <Name>Convert number to string</Name> <CommandLine>Examp1.EXE</CommandLine> <Input>1</Input> <Output>One</Output> </Test> <Test TestId="0002" TestType="CMD"> <Name>Find succeeding characters</Name> <CommandLine>Examp2.EXE</CommandLine> <Input>abc</Input> <Output>def</Output> </Test> <Test TestId="0003" TestType="GUI"> <Name>Convert multiple numbers to strings</Name> <CommandLine>Examp2.EXE /Verbose</CommandLine> <Input>123</Input> <Output>One Two Three</Output> </Test> <Test TestId="0004" TestType="GUI"> <Name>Find correlated key</Name> <CommandLine>Examp3.EXE</CommandLine> <Input>a1</Input> <Output>b1</Output> </Test> <Test TestId="0005" TestType="GUI"> <Name>Count characters</Name> <CommandLine>FinalExamp.EXE</CommandLine> <Input>This is a test</Input> <Output>14</Output> </Test> <Test TestId="0006" TestType="GUI"> <Name>Another Test</Name> <CommandLine>Examp2.EXE</CommandLine> <Input>Test Input</Input> <Output>10</Output> </Test> </Tests>
C#用法…
XElement root = XElement.Load("TestConfig.xml"); IEnumerable<XElement> tests = from el in root.Elements("Test") where (string)el.Element("CommandLine") == "Examp2.EXE" select el; foreach (XElement el in tests) Console.WriteLine((string)el.Attribute("TestId"));
此代码产生以下输出:0002 0006
根据您想要的文档types,您可以使用XmlDocument.LoadXml
或XDocument.Load
。
尝试这个:
var myXmlDocument = new XmlDocument(); myXmlDocument.Load(theString);