查询XML文档

时间:2012-11-11 10:55:29

标签: c# xml linq xml-parsing linq-to-xml

我正在尝试查询xml文档,但是这段代码没有读取带有封闭标记符号的xml部分,但是读取了很好的xelement。谁能发现我做错了什么?

我有程序生成的XML文档,它提供了封闭的标记文件,因此现在是一个问题..

<?xml version="1.0" encoding="utf-8" ?>
<Student>

 <Person name="John" city="Auckland" country="NZ" />

 <Person>
    <Course>GDICT-CN</Course>
    <Level>7</Level>
    <Credit>120</Credit>
    <Date>129971035565221298</Date>
 </Person>
 <Person>
    <Course>GDICT-CN</Course>
    <Level>7</Level>
    <Credit>120</Credit>
    <Date>129971036040828501</Date>
 </Person>
</Student>
class Program
{
    static void Main(string[] args)
    {
        XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");
        IEnumerable<XElement> rows = from row in xDoc.Descendants("Person") select row;

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

            foreach(XAttribute xatt in attlist)
            {
            Console.WriteLine(xatt);
            }
            Console.WriteLine("-------------------------------------------");
        }
        Console.ReadLine();

    }
}

2 个答案:

答案 0 :(得分:0)

由于您已将Course和其他属性添加为XElement,因此您需要循环使用XElements而不是属性 -

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

    foreach (XAttribute xatt in attlist)
    {
       Console.WriteLine(xatt);
    }
    foreach (XElement elemnt in xEle.Descendants())
    {
       Console.WriteLine(elemnt.Value);
    }
    Console.WriteLine("-------------------------------------------");
}

答案 1 :(得分:0)

首先,您必须导航到Person级别并遍历Persons,然后对于每个Person,您可以迭代其属性。

    private static void Main(string[] args)
    {
        //string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        //XDocument xDoc = XDocument.Load(path + "\\Student Data\\data.xml");
        XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");
        IEnumerable<XElement> xElements = xDoc.Descendants("Person");
        foreach (XElement element in xElements)
        {
            foreach (XAttribute attribute in element.Attributes())
            {
                Console.WriteLine(attribute);
            }
            Console.WriteLine("-------------------------------------------");
        }
        Console.ReadLine();
    }