XML c#多重记录

本文关键字:记录 XML | 更新日期: 2023-09-27 18:09:01

我有这个xml,我失去了阅读它,请有人帮助吗?

<?xml version = "1.0" encoding = "utf-8"?>
<root>
    <batch> 
    <field   level = "batch" name = "VoucherNumber" value = "00018"/>
    <field   level = "batch" name = "FinancialYear" value = "1996"/>
    <field   level = "batch" name = "CountNumber" value = "00018"/>
    <field   level = "batch" name = "CountDate" value = "1416-08-16"/>
    <field   level = "batch" name = "Total" value = "214000.0"/>
    <field   level = "batch" name = "CuttOf" value = "0.0"/>
    <field   level = "batch" name = "Net" value = "214000.0"/>
    <field   level = "batch" name = "Comment" value = "1"/>
    <field   level = "batch" name = "DailyNumber" value = "00018"/>
    <field   level = "batch" name = "DailyDate" value = "1416-09-01"/>
    <field   level = "batch" name = "Year" value = "1416"/>
    <field   level = "batch" name = "Section" value = "1"/>
    </batch> 
</root>

我试图提取所有的名称和值,并返回它们,我的代码如下:

private string ReadXML(string filename)
{
string str = "";
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlNodeList nodelist = doc.SelectNodes("/root/batch");
foreach (XmlNode node in nodelist)
{
str += node["name"].InnerText + node["value"].InnerText;
}
return str;
}

XML c#多重记录

"name"answers"value"是XML节点的属性。访问它们:

node.Attributes["name"].Value;
node.Attributes["value"].Value;

那么,这一行应该看起来像:

str += node.Attributes["name"].Value + node.Attributes["value"].Value;

我发现LinqToXml更容易使用

var dict = XDocument.Load(filename)
           .Descendants("field")
           .ToDictionary(f => f.Attribute("name").Value, f => f.Attribute("value").Value);

foreach(var kv in dict)
{
    Console.WriteLine(kv.Key + " " + kv.Value);
}

您需要更改所选节点以查找字段节点。您还需要访问foreach循环中节点的属性,如下所示:

XmlNodeList nodelist = doc.SelectNodes("/root/batch/field");
foreach (XmlNode node in nodelist)
{
    str += node.Attributes["name"].InnerText + node.Attributes["value"].InnerText;
}

您也可以将.InnerText更改为.Value,但两者都为我工作

XDocument也可以用来代替XMLDocument:

private string ReadXML(string filename)
{
    string str = "";
    XDocument doc = XDocument.Load(filename);
    IEnumerable<XElement> rows = doc.Root.Descendants("field");
    foreach (XElement node in rows)
    {
       str += node.Attribute("name").Value + node.Attribute("value").Value;
    }
    return str;
}

您可以在这里尝试:https://dotnetfiddle.net/CaQ6T2

我将使用LinqToXml并这样做:

private string ReadXML(string filename)
{
    return String.Join("",
        from d in XDocument.Load(filename).Descendants("field")
        let name = d.Attribute("name").Value
        let value = d.Attribute("value").Value
        from x in new [] { name, value }
        select x);
}