我有一个名为RESTORE.XML的XML文档 它具有这些价值......
<EmployeeDetails>
<EmployeeID>156824</EmployeeID>
<EmployeeName>ALEX</EmployeeName>
<EmployeeAge>29</EmployeeAge>
</EmployeeDetails>
从我的c#应用程序中我想读取这三个值并将其存储在3个不同的变量中。
如何使用c#?感谢。
答案 0 :(得分:5)
这应该有效:
using System.Xml.Linq;
XDocument xdoc = XDocument.Load("RESTORE.XML");
xdoc.Descendants("EmployeeID").First().Value;
xdoc.Descendants("EmployeeName").First().Value;
答案 1 :(得分:1)
试试这个:
XElement xml = XElement.Parse(@"
<EmployeeDetails>
<EmployeeID>156824</EmployeeID>
<EmployeeName>ALEX</EmployeeName>
<EmployeeAge>29</EmployeeAge>
</EmployeeDetails>");
int EmployeeID = int.Parse(xml.Element("EmployeeID").Value);
string EmployeeName = xml.Element("EmployeeName").Value;
int EmployeeAge = int.Parse(xml.Element("EmployeeAge").Value);
但是用xml文件加载代替解析......
答案 2 :(得分:0)
XmlDocument doc = new XmlDocument();
doc.Load("restore.xml" );
foreach (XmlNode nd in doc.DocumentElement.SelectNodes( "xml/entry" ))
{
...
}
答案 3 :(得分:0)
假设在我们的示例中,我们有一个带有根节点Reports的xml,并且有嵌套的子节点Reports,我们需要遍历每个孩子
sample.xml
<?xml version="1.0" encoding="utf-8" ?>
<Reports>
<Report>
<Code>CP</Code>
<RepeatStyle>Weekly</RepeatStyle>
</Report>
<Report>
<Code>USS</Code>
<Name>User Snapshot</Name>
<RepeatStyle>Monthly</RepeatStyle>
</Report>
<Report>
<Code>USS</Code>
<Name>Failed Logon Report</Name>
<RepeatStyle>Monthly</RepeatStyle>
</Report>
<Report>
<Code>USS</Code>
<Name>Failed Logon Report</Name>
<RepeatStyle>Monthly</RepeatStyle>
</Report>
</Reports>
在这里,我们可以利用System.Xml.XmlDocument来读取目标位置中提供的Xml文件,并使用System.Xml.XmlNodeList来拾取某些节点
XmlDocument serverDoc = new XmlDocument();
serverDoc.Load("sample.xml");
XmlNodeList xml = serverDoc.SelectNodes("Reports/Report");
foreach (XmlNode node in xml)
{
var code = node.SelectSingleNode("Code").InnerText;
var repeatStyle = node.SelectSingleNode("RepeatStyle").InnerText;
}