C# 使用 Visual studio 生成的 class 从 xml 节点获取所有文本,包括 xml 标记
C# Get all text from xml node including xml markup using Visual studio generated class
使用 xml 到 visual studio 中的 c# 功能将下面的 xml 标记转换为 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>
转换后的class包含
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class booksBookAuthorName
{
private byte refField; // 1
private string[] textField; // 2
我们需要的是Author-1<ref>1</ref>
作为阅读作者姓名时的输出,通过保留标签。
我们已经尝试了 https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmltextattribute(v=vs.110).aspx 属性。但没有希望。
有线索吗??
您可以使用该元素的 [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
:
[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
class。
示例 fiddle showing deserialization of a complete set of classes corresponding to your XML, generated initially from http://xmltocsharp.azurewebsites.net/,之后根据需要修改 Author
。
使用 xml 到 visual studio 中的 c# 功能将下面的 xml 标记转换为 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>
转换后的class包含
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class booksBookAuthorName
{
private byte refField; // 1
private string[] textField; // 2
我们需要的是Author-1<ref>1</ref>
作为阅读作者姓名时的输出,通过保留标签。
我们已经尝试了 https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmltextattribute(v=vs.110).aspx 属性。但没有希望。
有线索吗??
您可以使用该元素的 [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
:
[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
class。
示例 fiddle showing deserialization of a complete set of classes corresponding to your XML, generated initially from http://xmltocsharp.azurewebsites.net/,之后根据需要修改 Author
。