如何从C#中的xml XDocument中获取数据?

时间:2014-12-02 22:46:37

标签: c# xml

我有一个通过Web服务获得的XML文件。文件看起来像这样:

<Z_STU_CRS_TRNS_DOC xmlns="http://testurl">
    <Z_STATUS_CODE>0</Z_STATUS_CODE>
    <Z_STATUS_MSG>Success</Z_STATUS_MSG>
    <Z_STUDENT_ID_SUB_DOC xmlns="http://testurl">
        <Z_STU_ID>000999999</Z_STU_ID>
    </Z_STUDENT_ID_SUB_DOC>
    <Z_CRSE_SUB_DOC xmlns="http://testurl">
        <Z_COURSE xmlns="http://testurl">
            <Z_CRSE_DATA>9999|199901|TEST|9999|1|S|Scuba Diving| |XX</Z_CRSE_DATA>
        </Z_COURSE>
        <Z_COURSE xmlns="testurl">
            <Z_CRSE_DATA>9999|200001|TEST|999|3|A|English 101| |XX</Z_CRSE_DATA>
        </Z_COURSE>
    </Z_CRSE_SUB_DOC>
</Z_STU_CRS_TRNS_DOC>

我能够使用该服务并检查错误,但我实际上很难从XDocument xml文件中获取数据。

protected void webClient_DownloadStringCompleted(object sender, 
                                                 DownloadStringCompletedEventArgs e)
    { 
        if (e.Error != null)
            {
                errorLabel.Text = 
                  "The transaction failed. If you feel that you have reached " + 
                  "this in error, please contact the help desk at xxx-xxx-xxxx.";
                errorLabel.Visible = true;
                return;
            }

        XDocument xml = XDocument.Parse(e.Result);
        XNamespace ns = "http://testurl";


        //Look for error code from WS
        var field = xml.Descendants(ns + "Z_STATUS_CODE").FirstOrDefault();
        if (field != null)
        {
            if (Convert.ToInt32((string)field.Value) == 1)
            {
                errorLabel.Text = 
                   "The transaction failed, due to an invalid student id. If you " + 
                   "feel that you have reached this in error, please contact " + 
                   "the help desk at xxx-xxx-xxxx.";
                errorLabel.Visible = true;
                return;
            }
        }

我尝试了许多不同的方法,但似乎没有任何帮助。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我明白了!发布以防其他人有类似问题。

    List<studentRecord> studentCourses = new List<studentRecord>();
    XmlReader reader = xml.CreateReader();
    // Get elements
    while (reader.Read()) 
    {
        if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "Z_CRSE_DATA"))
        {
            reader.Read();
            if (reader.NodeType == XmlNodeType.Text)
            {
                studentRecord stuRec = new studentRecord();
                stuRec.rawData = reader.Value;
                studentCourses.Add(stuRec);
            }
        }
    }
    reader.Close();

答案 1 :(得分:-1)

您可以读取节点列表,并根据其名称读取节点的值。

需要更多的工作,因为你必须完成所有节点本身,但是你可以这样做

class Program
{
    static void Main(string[] args)
    {
        string xmldata = @"<Z_STU_CRS_TRNS_DOC xmlns=""http://testurl"">
<Z_STATUS_CODE>0</Z_STATUS_CODE>
<Z_STATUS_MSG>Success</Z_STATUS_MSG>
<Z_STUDENT_ID_SUB_DOC xmlns=""http://testurl"">
    <Z_STU_ID>000999999</Z_STU_ID>
</Z_STUDENT_ID_SUB_DOC>
<Z_CRSE_SUB_DOC xmlns=""http://testurl"">
    <Z_COURSE xmlns=""http://testurl"">
        <Z_CRSE_DATA>9999|199901|TEST|9999|1|S|Scuba Diving| |XX</Z_CRSE_DATA>
    </Z_COURSE>
    <Z_COURSE xmlns=""testurl"">
        <Z_CRSE_DATA>9999|200001|TEST|999|3|A|English 101| |XX</Z_CRSE_DATA>
    </Z_COURSE>
</Z_CRSE_SUB_DOC>
</Z_STU_CRS_TRNS_DOC>";
        string errorTag = "Z_STATUS_CODE",
            statusTag = "Z_STATUS_MSG";

        XDocument xml = XDocument.Parse(xmldata);
        XNamespace ns = "http://testurl";
        int errorCode = -1;
        string statusMessage = string.Empty;

        using (XmlReader reader = xml.CreateReader())
        {
            while (reader.Read())
            {
                if (reader.NodeType != XmlNodeType.Element)
                {
                    continue;
                }
                if (!string.Equals(reader.Name, errorTag) &&
                    !string.Equals(reader.Name, statusTag))
                {
                    continue;
                }
                string currentName = reader.Name;
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                    if (reader.NodeType != XmlNodeType.Text)
                    {
                        continue;
                    }
                    if (string.Equals(currentName, errorTag))
                    {
                        errorCode = int.Parse(reader.Value);
                    }
                    if (string.Equals(currentName, statusTag))
                    {
                        statusMessage = reader.Value;
                    }
                    break;
                }
            }
        }
        if (errorCode == -1)
        {
            // no tag found
            Console.WriteLine("No tag found named: {0}", errorTag);
        }
        else if (errorCode == 0)
        {
            Console.WriteLine("Operation was a success!");
        }
        else
        {
            Console.WriteLine("Operation failed with error code {0}", errorCode);
        }
        if (!string.IsNullOrWhiteSpace(statusMessage))
        {
            Console.WriteLine("Status message: {0}", statusMessage);
        }
        Console.ReadLine();
    }
}