2015-08-20 47 views
0

我有这个XML,我迷路了,请任何人都可以帮忙?xml c#多个记录

<?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; 
} 
+0

可能重复[阅读XML属性使用XmlDocument](http://stackoverflow.com/questions/933687/read-xml-attribute-using-xmldocument) – MethodMan

回答

0

“名”和“价值”是XML节点的属性。要访问它们:

​​

所以,这条线应该是这个样子:

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

谢谢。这样可行。我只需要做一点改动就可以在XmlNodeList中包含字段节点nodelist = doc.SelectNodes(“/ root/batch/field”) –

0

我发现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); 
} 
+0

很棒。我想使用你的代码,但是我可以首先知道它的执行速度是否比我的代码快?因为我需要在数百万个文档上运行它。 –

+0

@AbdH。 http://ericlippert.com/2012/12/17/performance-rant/ – Eser

0

你需要改变你的选择的节点,寻找现场节点。您还需要访问你的foreach循环节点的属性,这将是这个样子:

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

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

0

的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

0

我会去与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); 
}