0

我正在尝试查询一个 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();

    }
}
4

2 回答 2

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("-------------------------------------------");
}
于 2012-11-11T11:05:30.023 回答
0

首先,您必须导航到 Person 级别并遍历 Person,然后对于每个 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();
    }
于 2012-11-11T11:24:39.783 回答