[英]C# deserialize Xml attribute to value without wrapping it with class
I'm trying to deserialize xml below: 我正在尝试反序列化xml如下:
<venue href="http://SomeUrl">
<location id="ABC"/>
<title>Some title</title>
</venue>
When I wrap it with class like below XmlSerializer
works like charm 当我用下面的类包装它时,
XmlSerializer
就像魅力一样
[XmlRoot(ElementName = "venue")]
public class VenueModel
{
[XmlElement("location")]
public Location Location;
[XmlElement("title")]
public string Title;
[XmlAttribute("href")]
public string Href;
}
public class Location
{
[XmlAttribute("id")]
public string Id;
}
But in my opinion wrapping simple string from Location
into separate class it's quite dull solution. 但是在我看来,将简单的字符串从
Location
包装到单独的类中它是一个相当枯燥的解决方案。 What I would like to achieve is to create simpler flatten model like below: 我想要实现的是创建更简单的展平模型,如下所示:
[XmlRoot(ElementName = "venue")]
public class VenueModel2
{
[SomeMagicAttribute]
public string LocationId;
[XmlElement("title")]
public string Title;
[XmlAttribute("href")]
public string Href;
}
so first question? 第一个问题? is it possible using C#
System.Xml.Serialization
? 是否可以使用C#
System.Xml.Serialization
? If it is, what is the magic attribute to get this data? 如果是,获取此数据的神奇属性是什么?
what I found is that first i need to apply xsl translation (as the one below) to input xml 我发现首先我需要应用xsl转换(如下所示)来输入xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="no"/>
<xsl:template match="/">
<venue>
<href><xsl:value-of select="/venue/@href" /></href>
<locationId><xsl:value-of select="/venue/location/@id" /></locationId>
<title><xsl:value-of select="/venue/title" /></title>
</venue>
</xsl:template>
</xsl:stylesheet>
and then output xml looks like this: 然后输出xml看起来像这样:
<venue>
<href>SomeUrl</href>
<locationId>ABC</locationId>
<title>Some title</title>
</venue>
which than can be deserialised to the form i want it to be. 这可以反序列化为我想要的形式。 and applyink this translations in C# code is described here: C# How to perform a live xslt transformation on an in memory object?
并且在这里描述了C#代码中的这些翻译: C#如何在内存对象中执行实时xslt转换?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.