序列化具有同一标记中的文本和元素的 xml 文档

本文关键字:文本 元素 文档 xml 序列化 | 更新日期: 2023-09-27 18:35:09

是否可以在 C# 中序列化 xml 文档以生成此类标记

...
<myTag attr="tag">
    this is text
    <a href="http://yaplex.com">link in the same element</a>
</myTag>
...

我发现的唯一一种方法是将 myTag 的内容作为字符串

myTag.Value = "text <a ...>link</a>"; 

但我想让它在 C# 中作为对象,所以 a 标签将是一个对象

序列化具有同一标记中的文本和元素的 xml 文档

public class myTag
{
    [XmlAttribute]
    public string attr;
    [XmlText]
    public string text;
    public Anchor a;
}
[XmlRoot("a")]
public class Anchor
{
    [XmlAttribute]
    public string href;
    [XmlText]
    public string text;
}

-

var obj = new myTag() { 
    attr = "tag", 
    text = "this is text", 
    a = new Anchor() { 
        href = "http://yaplex.com",
        text="link in the same element" 
    } 
}; 
XmlSerializer ser = new XmlSerializer(typeof(myTag));
StringWriter wr = new StringWriter();
XmlWriter writer = XmlTextWriter.Create(wr, new XmlWriterSettings() { OmitXmlDeclaration = true });
var ns = new XmlSerializerNamespaces();
ns.Add("","");
ser.Serialize(writer,obj, ns);
string result = wr.ToString();

如果你实际上不想从类序列化,你可以像这样构造你的xml:

XElement xmlTree = new XElement("Root", 
    new XElement("myTag", 
    new XAttribute("attr", "tag"), 
    new XText("this is text"), 
    new XElement("a", "link in the same element", 
    new XAttribute("href", "http://yaplex.com"))));