Sau*_*abh 85
此代码示例取自Jan Slama编写的csharp-examples.net:
要在XML文件中查找节点,可以使用XPath表达式.方法XmlNode.SelectNodes返回由XPath字符串选择的节点列表.方法XmlNode.SelectSingleNode查找与XPath字符串匹配的第一个节点.
XML:
Run Code Online (Sandbox Code Playgroud)<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
码:
Run Code Online (Sandbox Code Playgroud)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); }
alm*_*ori 17
使用Linq到xml
添加对System.Xml.Linq的引用
并使用
XDocument.Parse(string xmlString)
Run Code Online (Sandbox Code Playgroud)
编辑:示例如下,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>
Run Code Online (Sandbox Code Playgroud)
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"));
Run Code Online (Sandbox Code Playgroud)
此代码生成以下输出:0002 0006
归档时间: |
|
查看次数: |
172504 次 |
最近记录: |