XmlAttributeCollection无法从xml获取属性

时间:2011-07-25 20:49:21

标签: c# mysql xml

我正在使用System.Xml从我的xml file获取属性。

似乎我在某处找到的代码能够正确地找到节点但是它不能识别属性(这很奇怪,因为我也用System.Xml创建了这个xml文件):

DataSet task_data = new DataSet("Root");
adapter.Fill(task_data); // MySqlDataAdapter is being used here
task_data.WriteXml(path, XmlWriteMode.WriteSchema);

所以我不知道为什么在互联网上可以找到的任何其他xml工作,而我用同一模块创建的xml不...

using System;
using System.Xml;
using System.IO;

public class Catalog
{
private XmlDocument xmldoc;
private string path = @"C:\Users\Me\Desktop\task.xml";

public static void Main()
{
    Catalog c = new Catalog();
}

public Catalog()

//Constructor
{
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    xmldoc = new XmlDocument();
    xmldoc.Load(fs);
    DisplayCatalog();
}

// Method for Displaying the catalog

private void DisplayCatalog()
{
    XmlNodeList xmlnode = xmldoc.GetElementsByTagName("task");
    Console.WriteLine("Here is the list of catalogs\n\n");

    for (int i = 0; i < xmlnode.Count; i++)
    {
        XmlAttributeCollection xmlattrc = xmlnode[i].Attributes; //HERE IS THE PROBLEM!!!

        Console.Write(xmlnode[i].FirstChild.Name);
        Console.WriteLine(":\t\t" + xmlnode[i].FirstChild.InnerText);


        Console.Write(xmlnode[i].LastChild.Name);
        Console.WriteLine(":\t" + xmlnode[i].LastChild.InnerText);
        Console.WriteLine();
    }

    Console.WriteLine("Catalog Finished");
}
//end of class

}

1 个答案:

答案 0 :(得分:2)

这是你连接到contins的xml,没有属性只有节点。

<?xml version="1.0" standalone="yes"?>
<Root>
  <task>
    <TaskId>1</TaskId>
    <TaskDelegatorNote>Presentation</TaskDelegatorNote>
    <StartTime>PT10H</StartTime>
    <EndTime>PT13H</EndTime>
    <TaskEndDate>2011-01-02T00:00:00+00:00</TaskEndDate>
    <TaskContractorNote>Done</TaskContractorNote>
    <TaskStatus>3</TaskStatus>
    <LastModification>Me, 2003-05-15 13:48:59</LastModification>
  </task>
  <task>
    <TaskId>2</TaskId>
    <TaskDelegatorNote>It must be done.</TaskDelegatorNote>
    <StartTime>PT10H</StartTime>
    <EndTime>PT13H</EndTime>
    <TaskEndDate>2011-01-02T00:00:00+00:00</TaskEndDate>
    <TaskContractorNote />
    <TaskStatus>2</TaskStatus>
    <LastModification>Admin, 2009-08-04 10:30:49</LastModification>
  </task>
</Root>

这是一个带有TaskId属性的xml snippint

   <task TaskId = 1>
   </task>

修复此更改

      Console.Write(xmlattrc[0].Name);
      Console.WriteLine(":\t\t" + xmlattrc[0].Value);

        Console.Write(xmlnode[0].ChildNodes[0].Name);
        Console.WriteLine(":\t\t" + xmlnode[0].ChildNodes[0].Value);

您的输出将是

Here is the list of catalogs


TaskId:
TaskId:         1
LastModification:       Me, 2003-05-15 13:48:59

TaskId:
TaskId:         2
LastModification:       Admin, 2009-08-04 10:30:49

Catalog Finished
Press any key to continue . . .

另外,您应该查看LinqToXML以了解对xml节点进行投影的其他方法