XML反序列化如何遍历第三个孩子

时间:2019-01-30 04:16:04

标签: c# xml

我有此Web服务可以重新调整该xml文件

<QCalls ts="Wed Jan 30 03:05:16 2019 UTC" cts="Wed Jan 30 03:04:04 2019 UTC" tzo="-28800" al="false">
 <Q id="815" n="Lo" wt="506098" ch="5" cwt="470" ct="3" co="4" ca="0" cw="9" awt="119366" act="84" cbh="2" ofi="0" ofo="0" catqos="0" dlro="336">
  <phone id="815" n="Lo"" wt="0" ch="1" cwt="1" ct="1" co="1" ca="0" cw="0" awt="0" act="417" cbh="2" ofi="0" ofo="0" catqos="0"/>
 </Q>
 <Q id="819" n="Hi" wt="70780" ch="2" cwt="156" ct="1" co="1" ca="0" cw="3" awt="51904" act="91" cbh="2" ofo="0" catqos="0" dlro="41">
  <phone id="819" n="Hi" wt="0" ch="1" cwt="1" ct="1" co="1" ca="0" cw="0" awt="0" act="181" cbh="2" ofo="0" catqos="0"/>
 </Q>
</QCalls>

我正在使用xmldeserializer从中检索数据。我需要位于XML文件第3级的phone标签数据。但是问题是当我检索它时。它仅获取第一个phone数据,我无法获取依赖于第二个Q的第二个数据。我在c#上具有这些代码以检索数据

[XmlRoot("MultipleFilters")]
public class MultipleFilters
{
   [XmlElement("QCalls")]
   public QCalls QCalls { get; set; }
}

public class QCalls
{
    [XmlAnyElement("Q")]
    public Phone phone { get; set; }
}
public class Phone
{
    [XmlElement("phone")]
    public List<QItem> Items { get; set; }
}
public class QItem
{
    [XmlAttribute("id")]
    public int id { get; set; }
    [XmlAttribute("n")]
    public string queue { get; set; }
    [XmlAttribute("cw")]
    public int cw { get; set; }
    [XmlAttribute("cwt")]
    public int cwt { get; set; }
}

calls = (MultipleFilters)serializer.Deserialize(response.GetResponseStream());

如何获取XML文件中的所有数据?

2 个答案:

答案 0 :(得分:0)

您的类结构不完全符合XML,应该是这样的:

class Phone {...}
class Q {
...
  [XmlElement("phone")]
  Phone Phone {get;set;}
...
}
class QCalls{
...
  [XmlElement("Q")]
  List<Q> QItems {get;set;}
...
}

答案 1 :(得分:0)

XmlArray采用两级xml标记,并置于1类中。每个xml元素都有一个类,因此不需要两个使用属性数组。你的课错了,所以我修好了。我还使用了文件而不是流来进行测试。下面的代码已经过测试并且可以正常工作。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(QCalls));

            QCalls qCalls = (QCalls)serializer.Deserialize(reader);
        }
    }
    [XmlRoot("QCalls")]
    public class QCalls
    {
        [XmlElement("Q")]
        public List<Q> q { get; set; }
    }
    [XmlRoot("Q")]
    public class Q
    {
        [XmlElement("phone")]
        public Phone phone { get; set; }
    }
    [XmlRoot("phone")]
    public class Phone
    {
        [XmlAttribute("id")]
        public int id { get; set; }
        [XmlAttribute("n")]
        public string queue { get; set; }
        [XmlAttribute("cw")]
        public int cw { get; set; }
        [XmlAttribute("cwt")]
        public int cwt { get; set; }
    }



}