C# Get all text from xml node including xml markup using Visual studio generated class

浪尽此生 提交于 2019-12-20 04:10:26

问题


Using xml to c# feature in visual studio converted the below xml markup into C# class.

<books>
<book name="Book-1">
<author>
<name>Author-1<ref>1</ref></name>
</author>
</book>
<book name="Book-2">
<author>
<name>Author-1<ref>1</ref></name>
</author>
</book>
</books>

The converted class contains

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class booksBookAuthorName
    {
        private byte refField;     // 1

        private string[] textField; // 2

What we need is Author-1<ref>1</ref>as the output when reading the author name, by keeping tags.

We have tried https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmltextattribute(v=vs.110).aspx attribute. But no hope.

Any clues ??


回答1:


You can use [XmlAnyElement("name")] to capture the XML of the <name> node of each author into an XmlElement (or XElement). The precise text you want is the InnerXml of that element:

[XmlRoot(ElementName = "author")]
public class Author
{
    [XmlAnyElement("name")]
    public XmlElement NameElement { get; set; }

    [XmlIgnore]
    public string Name
    {
        get
        {
            return NameElement == null ? null : NameElement.InnerXml;
        }
        set
        {
            if (value == null)
                NameElement = null;
            else
            {
                var element = new XmlDocument().CreateElement("name");
                element.InnerXml = value;
                NameElement = element;
            }
        }
    }
}

This eliminates the need for the booksBookAuthorName class.

Sample fiddle showing deserialization of a complete set of classes corresponding to your XML, generated initially from http://xmltocsharp.azurewebsites.net/ after which Author was modified as necessary.



来源:https://stackoverflow.com/questions/40715261/c-sharp-get-all-text-from-xml-node-including-xml-markup-using-visual-studio-gene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!