【发布时间】:2020-04-27 16:15:38
【问题描述】:
我从周五开始就在谷歌上搜索这个,整个早上都在扯头发。
我有一些从 netforum 返回的 xml,这些 xml 是从对 WEBCommitteeGetCommitteeListAsync 的调用中返回的。
返回的响应不是xmldocument,WEBCommitteeGetCommitteeListResult里面有一系列子节点。每个节点看起来像下面的项目(但我更改了数据以保护无辜者):
<Result xmlns="http://www.avectra.com/2005/">
<cmt_key>a guid I clipped out</cmt_key>
<cmt_code>ICTF</cmt_code>
<cmt_name>a committee name</cmt_name>
<cmt_ctp_code>Task Force</cmt_ctp_code>
<cmt_begin_date />
<cmt_end_date />
<cmt_description>the committee description</cmt_description>
</Result>
我使用https://xmlgrid.net/xml2xsd.html 创建了一个模型类,如下所示:
public class NFCommittee
{
[XmlRoot(ElementName = "Result")]
public class Result
{
[XmlElement(ElementName = "cmt_key")]
public string Cmt_key { get; set; }
[XmlElement(ElementName = "cmt_code")]
public string Cmt_code { get; set; }
[XmlElement(ElementName = "cmt_name")]
public string Cmt_name { get; set; }
[XmlElement(ElementName = "cmt_ctp_code")]
public string Cmt_ctp_code { get; set; }
[XmlElement(ElementName = "cmt_begin_date")]
public string Cmt_begin_date { get; set; }
[XmlElement(ElementName = "cmt_end_date")]
public string Cmt_end_date { get; set; }
[XmlElement(ElementName = "cmt_description")]
public string Cmt_description { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
}
}
我用来反序列化每个子节点的代码是:
XmlSerializer serializer = new XmlSerializer(typeof(NFCommittee));
System.Xml.XmlNodeReader oReader = new System.Xml.XmlNodeReader(childNode);
NFCommittee convertedItem = (NFCommittee)serializer.Deserialize(oReader);
我得到的错误是 {"http://www.avectra.com/2005/'> 不是预期的。"}
显然我更喜欢一次性转换整个子节点列表,但我什至无法转换单个子节点,我不知道为什么。
编辑:原始类看起来像这样,但结果完全相同,所以我尝试取出命名空间。
[XmlRoot(ElementName = "Result", Namespace = "http://www.avectra.com/2005/")]
public class Result
{
[XmlElement(ElementName = "cmt_key", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_key { get; set; }
[XmlElement(ElementName = "cmt_code", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_code { get; set; }
[XmlElement(ElementName = "cmt_name", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_name { get; set; }
[XmlElement(ElementName = "cmt_ctp_code", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_ctp_code { get; set; }
[XmlElement(ElementName = "cmt_begin_date", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_begin_date { get; set; }
[XmlElement(ElementName = "cmt_end_date", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_end_date { get; set; }
[XmlElement(ElementName = "cmt_description", Namespace = "http://www.avectra.com/2005/")]
public string Cmt_description { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
}
【问题讨论】:
-
您缺少命名空间(如 abc)来自:xmlns="avectra.com/2005" To xmlns:abc="avectra.com/2005"
-
那个在里面,但它不起作用。所以我把它拿出来了。我刚刚更新了上面的代码以显示它的外观。
标签: c# xml serialization