简体   繁体   中英

use c# how to read xml file

<Reports>
  <Databases>
    <Database>Axxest</Database>
    <Database>Axxest2</Database>
  </Databases>
</Reports>

how to read Axxest , Axxest2 use c# to read xml file like this?

I try this:

XmlDocument xld = new XmlDocument();
xld.Load(XmlPath);
XmlNodeList xnl = xld.SelectSingleNode("Reports").ChildNodes;
tableList.Clear();
foreach (XmlNode xn in xnl)
{
    tableList.Add(xn.InnerText);
} 

but something wrong?

Try SelectNodes method and XPath :

XmlDocument xld = new XmlDocument();
xld.Load(XmlPath);
XmlNodeList xnl = xld.SelectNodes("Reports/Databases/Database");
foreach (XmlNode xn in xnl)
{
    tableList.Add(xn.InnerText);
}

See the Documentation's Example :

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();

If you want to find some nodes in a xml file, you can use XPath for query, and here is all you need in w3 schools .

If you debug the code, you can find the count of xnl is one, it only includes "Databases" node. "SelectSingleNode" means select one node, and in your code, "Reports" is first selected, then return its childnodes, which only contains "Databases". You can try Ria's code, use SelectNodes instead of SelectSingleNode. But you can still use "SelectSingleNode", try this:

XmlNodeList xnl = xld.SelectSingleNode("Reports/Databases").ChildNodes;  

Hope it's helpful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM