简体   繁体   English

获取也具有属性的XML元素的值

[英]Getting the value of an XML Element that also has attributes

I'm using the .NET XmlSerializer class to deserialize some XML document. 我正在使用.NET XmlSerializer类对一些XML文档进行反序列化。 In that document, I have an element that looks like that: 在该文档中,我有一个看起来像这样的元素:

<MyElement attr1="xxx" attr2="yyy">VALUE</MyElement>

This is a part of a bigger XML. 这是更大的XML的一部分。 I need to deserialize this string into an object, so I wrote: 我需要将此字符串反序列化为一个对象,所以我写道:

public class MyElement
{
    [XmlAttribute(AttributeName = "attr1")]
    public string attr1 { get; set; }

    [XmlAttribute(AttributeName = "attr2")]
    public string attr2  { get; set; }

    [??????????????]
    public string value { get; set; }
}

And I can't figure out what to put instead of the question marks in order to get the value of the element into the value. 而且我无法弄清楚要把元素的值放入值中要问的是什么而不是问号。

XmlTextAttribute : XmlTextAttribute

By default, the XmlSerializer serializes a class member as an XML element. 默认情况下,XmlSerializer将类成员序列化为XML元素。 However, if you apply the XmlTextAttribute to a member, the XmlSerializer translates its value into XML text. 但是,如果将XmlTextAttribute应用于成员,则XmlSerializer会将其值转换为XML文本。 This means that the value is encoded into the content of an XML element. 这意味着该值被编码到XML元素的内容中。

[XmlText]
public string Value { get; set; }

If the XmlTextAttribute does not work, you could use the XmlElementAttribute 如果XmlTextAttribute不起作用,则可以使用XmlElementAttribute

[XmlElement( DataType = "string", ElementName = "value" )]
public string value { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM