C#使用Visual Studio生成的类从xml节点获取所有文本,包括xml标记 [英] C# Get all text from xml node including xml markup using Visual studio generated class

查看:55
本文介绍了C#使用Visual Studio生成的类从xml节点获取所有文本,包括xml标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Visual Studio中使用xml to c#功能将下面的xml标记转换为C#类.

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>

转换后的类包含

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

        private string[] textField; // 2

我们需要的是通过保留 标签将 Author-1< ref> 1</ref> 作为读取作者姓名时的输出.

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

我们尝试了 https://msdn.microsoft.com/zh-CN/library/system.xml.serialization.xmltextattribute(v = vs.110).aspx 属性.但是没有希望.

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

任何线索??

推荐答案

您可以使用 会将每个作者的< name> 节点的XML捕获到一个 XmlElement (或 XElement ).您想要的确切文本是 InnerXml 该元素:

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;
            }
        }
    }
}

这消除了对 booksBookAuthorName 类的需要.

样本小提琴显示了最初由 http://xmltocsharp.azurewebsites.net/之后,根据需要修改了 Author .

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.

这篇关于C#使用Visual Studio生成的类从xml节点获取所有文本,包括xml标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆