使用同一标记中的text和element序列化xml文档

时间:2012-05-24 14:32:14

标签: c# xml serialization xhtml xml-serialization

是否可以在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-tag 将是一个对象

2 个答案:

答案 0 :(得分:1)

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();

答案 1 :(得分:1)

如果你真的不想从课程序列化,你可以像这样构建你的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"))));