<Reports>
<Databases>
<Database>Axxest</Database>
<Database>Axxest2</Database>
</Databases>
</Reports>
如何阅读Axxest
,Axxest2
使用c#来读取这样的xml文件?
我试试这个:
XmlDocument xld = new XmlDocument();
xld.Load(XmlPath);
XmlNodeList xnl = xld.SelectSingleNode("Reports").ChildNodes;
tableList.Clear();
foreach (XmlNode xn in xnl)
{
tableList.Add(xn.InnerText);
}
但有些不对劲?
答案 0 :(得分:1)
尝试SelectNodes
方法和XPath
:
XmlDocument xld = new XmlDocument();
xld.Load(XmlPath);
XmlNodeList xnl = xld.SelectNodes("Reports/Databases/Database");
foreach (XmlNode xn in xnl)
{
tableList.Add(xn.InnerText);
}
答案 1 :(得分:0)
StringBuilder output = new StringBuilder();
String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Items>
<Item>test with a child element <more/> stuff</Item>
</Items>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(output, ws))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
OutputTextBlock.Text = output.ToString();
答案 2 :(得分:0)
如果要在xml文件中找到一些节点,可以使用XPath进行查询,这就是w3 schools中所需的全部内容。
如果调试代码,可以发现xnl的计数是1,它只包含“Databases”节点。 “SelectSingleNode”表示选择一个节点,在您的代码中,首先选择“Reports”,然后返回其子节点,该子节点仅包含“数据库”。您可以尝试使用Ria的代码,使用SelectNodes而不是SelectSingleNode。但你仍然可以使用“SelectSingleNode”,试试这个:
XmlNodeList xnl = xld.SelectSingleNode("Reports/Databases").ChildNodes;
希望它对你有所帮助。