English 中文(简体)
同一标签中带有文本和元素的 xml 串行文档
原标题:Serialize xml document with text and element in the same tag

C# 中的 xml 文档能否序列化, 以生成这样的标签?

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

我找到的唯一方法就是 把我的Tag 内容当作字符串

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

但我希望在 C # 中将它作为对象, 所以“ 强” a- tag

最佳回答
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"))));




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签