C# 多种类型的XML反序列化
我正在将一个大型xml文档反序列化为一个C对象 我遇到了一个问题,同一行中有多个xml元素,在代码中正确地重新构造它们时遇到了困难 下面是一个代码段示例:C# 多种类型的XML反序列化,c#,xml,xml-deserialization,C#,Xml,Xml Deserialization,我正在将一个大型xml文档反序列化为一个C对象 我遇到了一个问题,同一行中有多个xml元素,在代码中正确地重新构造它们时遇到了困难 下面是一个代码段示例: <parent> <ce:para view="all"> Text <ce:cross-ref refid="123">[1]</ce:cross-ref> More Text <ce:italic>Italicized text</ce:italic&g
<parent>
<ce:para view="all">
Text <ce:cross-ref refid="123">[1]</ce:cross-ref> More Text <ce:italic>Italicized text</ce:italic> and more text here
</ce:para>
<ce:para>...</ce:para>
</parent>
我曾考虑将整个元素作为字符串引入,然后从中删除标记,但我不确定如何正确地将其反序列化。或者如果有更好的方法
免责声明:我无法更改XML文档,因为它来自第三方
谢谢一旦您将第三方XML反序列化为与XML模式直接匹配的对象,正如您在上面的示例中所做的那样,您应该能够根据Chris的请求在上使用,我将发布我的解决方案。因为我对linq查询不是很有经验,所以它可能可以用于细化
XDocument xdoc = xmlAdapter.GetAsXDoc(xmlstring);
IEnumerable<XElement> body = from b in xdoc.Descendants()
where b.Name.LocalName == "body"
select b;
IEnumerable<XElement> sections = from s in body.Descendants()
where s.Name.LocalName == "sections"
select s;
IEnumerable<XElement> paragraphs = from p in sections.Descendants()
where p.Name.LocalName == "para"
select p;
string bodytext = "";
if (paragraphs.Count() > 0)
{
StringBuilder text = new StringBuilder();
foreach (XElement p in paragraphs)
{
text.AppendFormat("{0} ", p.Value);
}
}
bodytext = text.ToString();
谢谢你,克里斯。通过使用XDocument和Linq获取我的文本,我最终做了一些不同的事情,但我会将您的答案标记为正确,因为我仍然遵循您的逻辑来获得结果。如果您有时间,请添加您的答案作为备选答案。我想看看你最终是如何实现它的。我添加了我的答案,克里斯。谢谢分享,尼克!p、 值的行为与node.InnerText非常相似
Text: {"Text", "More Text", "and more text here"}
Crossref: {"[1]"}
Italic: {"Italicized Text"}
XDocument xdoc = xmlAdapter.GetAsXDoc(xmlstring);
IEnumerable<XElement> body = from b in xdoc.Descendants()
where b.Name.LocalName == "body"
select b;
IEnumerable<XElement> sections = from s in body.Descendants()
where s.Name.LocalName == "sections"
select s;
IEnumerable<XElement> paragraphs = from p in sections.Descendants()
where p.Name.LocalName == "para"
select p;
string bodytext = "";
if (paragraphs.Count() > 0)
{
StringBuilder text = new StringBuilder();
foreach (XElement p in paragraphs)
{
text.AppendFormat("{0} ", p.Value);
}
}
bodytext = text.ToString();