我有一个字符串形式的xml。 比方说串如何使用XmlSerializer反序列化嵌套结构
<?xml version='1.0' encoding='utf-8' ?>
<parameter>
<name>max_amount</name>
<label>Max Amount</label>
<unit>Millions</unit>
<component>
<type>Combo</type>
<attributes>
<type>Integer</type>
<displayed>4</displayed>
<selected>0</selected>
<items>
<item>5</item>
<item>10</item>
<item>20</item>
<item>50</item>
</items>
</attributes>
</component >
</parameter>
我已经成功反序列化,并得到了它的对象是这样的:
[XmlRoot(ElementName = "parameter")]
public class Parameter
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("label")]
public string Label { get; set; }
[XmlElement("unit")]
public string Unit { get; set; }
[XmlElement("component")]
public Component Component { get; set; }
}
[XmlRoot(ElementName = "component")]
public class Component
{
[XmlElement("type")]
public string Type { get; set; }
[XmlElement("attributes")]
public Attributes Attributes { get; set; }
}
[XmlRoot(ElementName = "attributes")]
public class Attributes
{
[XmlElement("type")]
public string Type { get; set; }
[XmlElement("displayed")]
public string Displayed { get; set; }
[XmlElement("selected")]
public string Selected { get; set; }
[XmlArray("items")]
[XmlArrayItem("item", typeof(string))]
public List<string> Items { get; set; }
}
和我的主类是像这样的地方我访问XML的所有元素:
XmlSerializer deserializer = new XmlSerializer(typeof(Parameter));
XmlReader reader = XmlReader.Create(new StringReader(xmlstring));
Parameter parameter = (Parameter)deserializer.Deserialize(reader);
foreach (var item in parameter.Component.Attributes.Items)
{
Debug.WriteLine(item);
}
Debug.WriteLine(parameter.Component.Type);
Debug.WriteLine(parameter.Name);
Debug.WriteLine(parameter.Label);
Debug.WriteLine(parameter.Unit);
直到这里evrerything是好的,但如果xml是嵌套的,如果我有这样的xml:
<parameter>
....
....
....
</parameter>
<parameter>
....
....
....
</parameter>
详细:如果我的XML字符串是这样的:
<?xml version='1.0' encoding='utf-8' ?>
<parameter>
<name>max_amount</name>
<label>Max Amount</label>
<unit>Millions</unit>
<component>
<type>Combo</type>
<attributes>
<type>Integer</type>
<displayed>4</displayed>
<selected>0</selected>
<items>
<item>5</item>
<item>10</item>
<item>20</item>
<item>50</item>
</items>
</attributes>
</component >
</parameter>
<parameter>
<name>max_amount_again</name>
<label>Max Amount_again</label>
<unit>Millions_again</unit>
<component>
<type>Combo</type>
<attributes>
<type>Integer</type>
<displayed>41</displayed>
<selected>01</selected>
<items>
<item>50</item>
<item>100</item>
<item>200</item>
<item>500</item>
</items>
</attributes>
</component >
</parameter>
我将如何得到这个时间因素?,因为这里参数是“父”类,当我们反序列化它时,我们会得到parameter
的对象,以及我将如何访问第二个<parameter>..</parameter><parameter>..How to get the data here..</parameter>
?
所以,你想获得的参数列表? '列表'? –
merp
那么首先,第二个不是有效的XML文档,所以我想你不会反序列化那样的东西。 –
您有2个根XML元素 - 这是不允许的。将2''放入一个''中即可解析它。 –