使用LINQ解析XML文档(内部示例代码)

时间:2015-09-18 09:57:40

标签: c# xml

我是初学者,学习用C#编程,所以请耐心等待。我有一个相当复杂的XML结构,我正在工作:

<Tab name ="Hospital">
  <section name="billing" id="22-78" author="James B. Moore" ID="87329874">
  </section>
</Tab>
<Tab name ="Insurance">
  <section name="billing" id="22-90" author="Sarah B. Patterson" ID="234546">
  </section>
</Tab>
<Tab name ="Billing">
  <section name="billing" id="22-96" author="Oli Ward" ID="8979">
  </section>
</Tab>

我有以下代码:

//Method to get Tab Details
private static void GetTab(XDocument oXDocument, string p_Descendant, string p_Attribute)
{
    //Get Section List
    IEnumerable<XElement> rows = 
        from row in oXDocument.Descendants(p_Descendant) 
        select row;

    foreach (XElement xEle in rows)
    {
        IEnumerable<XAttribute> attList = 
            from att in xEle.DescendantsAndSelf().Attributes()
            select att;

        Console.WriteLine("Tab: " + (string)xEle.Attribute(p_Attribute));

        //Get Section Names
        string s_descendant = "section";
        string s_Attribute = "name";

        GetDetails(oXDocument, s_descendant, s_Attribute);
    }
}

//Method to get Section Details
private static void GetDetails(XDocument oXDocument, string p_Descendant, string p_Attribute)
{
    //Get Section List
    IEnumerable<XElement> rows = 
        from row in oXDocument.Descendants(p_Descendant)
        select row;


    foreach (XElement xEle in rows)
    {
        IEnumerable<XAttribute> attList = 
            from att in xEle.DescendantsAndSelf().Attributes()
            select att;

        Console.WriteLine("Section: " + (string)xEle.Attribute(p_Attribute));
    }
}

我认为我接近这个错误。我的逻辑似乎是;获取Tab Details,调用另一个获取属性值的方法,但这意味着我必须为每个属性值创建一个方法。有谁知道更好的方法?

我在上面阅读了一些MSDN文档和Youtube视频。

编辑:(抱歉)我想要实现的是如下控制台输出:

Tab: Hospital
  Section: Billing
    Values: id: 22-78, author: James B. Moore, ID: 87329874
Tab: Insurance
  Section: Billing
    Values: id: 22-90, author: Sara B. Patterson, ID: 234546

我正在尝试遍历XML和Tab元素的每个实例,我想像上面那样格式化到控制台。

我希望这很清楚。抱歉我的英文。

1 个答案:

答案 0 :(得分:0)

此代码应实现您提供的输出

var xe = XDocument.Parse(Xml);

foreach (var tab in xe.Descendants("Tab"))
{
    var tabName = tab.Attribute("name").Value;
    var sectionName = tab.Element("section").Attribute("name").Value;
    var sectionValues = tab.Element("section").Attributes()
        .Where(x => x.Name != "name")
        .Select(x => string.Format("{0}: {1}", x.Name, x.Value));

    Console.WriteLine("Tab: {0}\n\tSection: {1}\n\t\tValues: {2}", tabName, sectionName, string.Join(", ", sectionValues));
}

使用C#6.0字符串插值会看起来好多了,但我不会假设您使用的是VS2015。