1

Is it possible to serialize xml document in C# to produce such tags

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

The only one way I found is have content of myTag as string

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

but I want to have it as object in C#, so a-tag will be an object

4

2 回答 2

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();
于 2012-05-24T14:52:25.623 回答
1

If you don't actually want to serialize from class you can construct your xml like this:

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"))));
于 2012-05-24T14:57:15.473 回答