-1

http://api.serviceu.com/rest/events/occurrences?orgkey=613dc2ce-0b32-4926-8e7e-33ee279be1cb

我有上面有 n 次出现的 xml url。我需要阅读所有事件并将其加载到列表项中。如何使用 xml 阅读器做到这一点。

 XmlTextReader reader = new XmlTextReader(strURL);

 while (reader.Read())
 {

 }

例如,我如何阅读每个事件的 CategoryList、ContactEmail、Description。

谢谢。

4

4 回答 4

2

您可以使用XmlReader

using(XmlReader reader = XmlReader.Create("..."))
{
    while (reader.Read())
    {
        if (reader.IsStartElement())
        {
            switch (reader.Name)
            {
                case "CategoryList":
                    var cat = reader.ReadElementContentAsString();
                    break;
                case "ContactEmail":
                    var email = reader.ReadElementContentAsString();
                    break;
            }
        }
    }
}

XmlDocument白衣XPath

XmlDocument document = new XmlDocument();
document.Load("...");
foreach (XmlNode node in document.SelectNodes("//CategoryList"))
{
    var cat = node.InnerText;
}

foreach (XmlNode node in document.SelectNodes("//ContactEmail"))
{
    var email = node.InnerText;
}

或LB提到的 Linq-to-Xml 。

于 2012-07-16T18:16:19.770 回答
1

Linq2Xml 可以让生活更轻松。

XDocument xDoc = XDocument.Load("http://api.serviceu.com/rest/events/occurrences?orgkey=613dc2ce-0b32-4926-8e7e-33ee279be1cb");
var list = xDoc.Descendants("Occurrence")
            .Select(o => new Item
            {
                Category = (string)o.Element("CategoryList"),
                EMail = (string)o.Element("ContactEmail"),
                Description = (string)o.Element("Description"),
            })
            .ToList();


public class Item
{
    public string Category;
    public string EMail;
    public string Description;
}
于 2012-07-16T18:05:18.707 回答
0
XmlTextReader reader = new XmlTextReader(strURL);

    while (reader.Read())
    {
        switch(reader.Name)
         {
            case "ContactEmail":
                  //reader.ReadElementContentAsString();
              break;
             //...
         }
    }

我将为 XML 文档中的每个集合创建一个支持类。

于 2012-07-16T18:00:35.783 回答
0
[DataContract(Name = "Occurrence", Namespace = "")]
class Occurrence
{
    [DataMember]
    public string CategoryList { get; set; }
    [DataMember]
    public string ContactEmail { get; set; }
    [DataMember]
    public string Description { get; set; }
}
var ser = new DataContractSerializer(typeof(List<Occurrence>), "Occurrences", "");

List<Occurrence> objects = null;
using (var reader = XmlReader.Create(strURL))
{
    objects = (List<Occurrence>) ser.ReadObject(reader);
}
于 2012-07-16T18:25:49.887 回答