简体   繁体   English

如何创建一个可序列化的类来使用单个节点反序列化XML?

[英]How to create a serializable class to deserialize an XML with a single node?

I can't find a way to create a serializable class in C# to handle deserialization from an XML that has a single node, like this one: 我找不到在C#中创建可序列化类的方法来处理来自具有单个节点的XML的反序列化,如下所示:

<?xml version="1.0"?>
<code>
    GM47R4 5I3RR4 LUB
</code>

I've been trying using XSD.exe to first create the XSD and then the C# class but it didn't work. 我一直在尝试使用XSD.exe首先创建XSD然后再创建C#类,但它不起作用。

Thank you for your help. 谢谢您的帮助。

    var xmlSer = new XmlSerializer(typeof (Code));
    var code = new Code {Value = "xx"};
    var sb = new StringBuilder();
    var wri = new StringWriter(sb);
    xmlSer.Serialize(wri, code);
    Console.WriteLine(sb.ToString());

    [XmlRoot(ElementName = "Code")]
    public class Code
    {
        [XmlText]
        public string Value { get; set; }
    }

Outputs 输出

<?xml version="1.0" encoding="utf-16"?>
<Code xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
xx
</Code>

And can thus be used to deserialize your xml as well, namespaces will be ignored by default. 因此可以用于反序列化您的xml,默认情况下将忽略名称空间。

@woutervs' code is good if you really need a custom class. 如果你真的需要一个自定义类,@ woutervs的代码是好的。 For XML this simple, is it really necessary to create a separate class? 对于XML这么简单,是否真的有必要创建一个单独的类? Probably not, unless you have requirements you didn't include in your question. 可能不会,除非您有要求,否则您的问题中没有包含这些要求。

I'd just use the XDocument class: 我只是使用XDocument类:

const string xml = @"<?xml version=""1.0""?>
<code>
    GM47R4 5I3RR4 LUB
</code>";
XDocument document = XDocument.Parse(xml);

Console.WriteLine(document.Element("code").Value.Trim());

XDocument can easily be used to create XML, too: XDocument也可以轻松地用于创建XML:

var document = new XDocument(new XElement("code", "GM47R4 5I3RR4 LUB"));

Console.WriteLine(document);

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

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