我正在尝试使用相同的标签读取XML数据,但我无法获取所有数据。
示例XML代码:
<print_set>
<line align="center" weight="normal" font="Courier New" height="20">-------------------------------</line>
<line align="center" weight="normal" font="Courier New" height="20">MARRY BROWN FAMILY RESTAURANT</line>
<line align="center" weight="normal" font="Courier New" height="20">Anna Nagar East</line>
<line align="center" weight="normal" font="Courier New" height="20">AH 45, 4th Avenue</line>
<line align="center" weight="normal" font="Courier New" height="20">5000023</line>
<line align="center" weight="normal" font="Courier New" height="20">Shanthi Colony</line>
<line align="center" weight="normal" font="Courier New" height="20">Chennai</line>
<line align="center" weight="normal" font="Courier New" height="20">For Home Delivery : 46218777</line>
<line align="center" weight="normal" font="Courier New" height="20">OrderOnline:marrybrownindia.com</line>
<line align="center" weight="normal" font="Courier New" height="20">-------------------------------</line>
<line align="left" weight="normal" font="Courier New" height="20">Employee:vinod</line>
<line align="left" weight="normal" font="Courier New" height="20">Bill Number:Ma-70</line>
<line align="left" weight="normal" font="Courier New" height="20">Date:26/07/2014 Time:12:14 PM</line>
<line align="center" weight="normal" font="Courier New" height="20">-------------------------------</line>
</print_set>
我用来读它的代码:
XmlNodeList xnListCommon = xml.SelectNodes("/print_set");
foreach (XmlNode xn in xnListCommon)
{
company_name = xn["line"].InnerText;
font_style = xn["line"].Attributes["font"].Value;
weight = xn["line"].Attributes["weight"].Value;
alignment = xn["line"].Attributes["align"].Value;
height = Convert.ToInt32(xn["line"].Attributes["height"].Value);
}
答案 0 :(得分:1)
使用LINQ-to-XML,使用Descendants()非常简单。
从路径中,使用Load():
var doc = XDocument.Load("path-to-file");
或者,从现有的XML字符串中,使用Parse():
var doc = XDocument.Parse("your XML string");
然后,获取XML中的行:
var lines = doc.Root.Descendants("line");
如有必要,您可以保留元素名称。我不确定你到底做了什么,但你的循环看起来像这样:
foreach (var line in lines)
{
company_name = line.Value;
font_style = line.XAttribute("font").Value;
weight = line.XAttribute("weight").Value;
alignment = line.XAttribute("align").Value;
height = Convert.ToInt32(line.XAttribute("height").Value);
}