C# 使用C读取具有相同标记的xml数据#

C# 使用C读取具有相同标记的xml数据#,c#,xml,C#,Xml,我试图读取具有相同标记的XML数据,但无法获取所有数据 示例XML代码: <print_set> <line align="center" weight="normal" font="Courier New" height="20">-------------------------------</line> <line align="center" weight="normal" font="Courier New" height="2

我试图读取具有相同标记的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>

使用LINQtoXML,它相当简单,使用

从路径中,使用:

或者,从现有XML字符串中,使用:

然后,要获取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);
}

你们面临什么问题?那个么,你们不能得到什么数据?若我通过标记名行,我只得到第一个值,但。然后它就从循环中出来了。我想在不传递标记名的情况下获取xml数据,即使我的标记是相同的。@MDFayaz您想从这个xml中得到什么最终结果?牢记在当前循环之后,您将只有最后一行的值谢谢,但我希望我的代码也在2.0中运行,但2.0将不支持linq@MDFayaz您可能希望在您的问题中包括这一点。我将xml数据存储在一个字符串中,并将该字符串传递给方法,然后它在路径异常中显示非法字符可能是因为忽略示例中给出的“文件路径”字样;特定的XDocument方法需要的是路径,而不是XML内容。我将更新答案。非常感谢我现在得到了结果
var doc = XDocument.Parse("your XML string");
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);
}