【问题标题】:XML Element's element/attribute annotation in C#C# 中 XML 元素的元素/属性注释
【发布时间】:2016-04-04 20:56:54
【问题描述】:

是否可以通过 xml 注释获取元素的(子)元素或元素自己的属性,而无需幻像类?

示例当前代码片段: XML:

<root>
    ...
    <epno type="1">12</epno>
    ...
</root>

C# 类:

[XmlRoot("root")]
class Root {
    ...
    [XmlElement("epno")]
    public Epno epno;
    ...
}

class Epno { //"Phantom" class
    [XmlAttribute("type")]
    public int type;
    [XmlText]
    public int epno;
}

我想要的是删除那个 Epno 类并将这些道具移动到 Root 类中......

[XmlRoot("root")]
class Root {
    ...
    [XmlElement("epno")]
    [XmlAttribute("type")] // I need a solution for this...
    public int type;
    [XmlElement("epno")]
    public int epno;
    ...
}

还有一个地方,加号在哪里,我想得到一个元素的属性,这是另一个元素……比我想得到元素的元素值。

这是一个 Xml 示例:

<root>
    <rates>
        <permanent votes="100">6.54</permanent>
        <temprate votes="100">6.54</temprate>
    </rates>
</root>

这里我想将这些值放入根类,但在这种情况下,至少需要 2 个类来解析它。

那么,有没有一种方法可以通过注释反序列化这些类,而无需这些幻像类,也无需编写我自己的 xml 解析器?

【问题讨论】:

  • 对不起,“没有幻影类”是什么意思?
  • 查看第二个代码段,我的意思是在基本上不需要创建的虚拟类下,因为它也可以包含与根/父类相同的信息,如果您将数据保存到数据库,您将不会t 为该数据创建一个新表,只需将其连接到您的“原始”数据。在第二个代码片段中,Epno 类是一个幻像,因为将两个数据放入一个新类是没有用的......
  • 或者,我也可以这样说:我想从片段 2 创建代码片段 3,我需要反序列化的原始代码在片段 1 中。片段 4 是我的另一个数据需要反序列化,但这是第 2 级...

标签: c# xml annotations


【解决方案1】:

在 XML 序列化过程中,only XML 序列化属性无法获取根类的“一个子元素及其属性”并将其转换为其根类的元素。

但是,您可以通过以下方式获得所需的结果:

【讨论】:

  • 我害怕这个......基本上我需要这个,因为我想把它放到数据库中这些数据,但更正常的格式。那么,如果我使用 XMLIgnore 注释创建一个新的(或更多)属性并将这些“幻像”道具与新道具链接在一起,会发生什么? (如果存在,我需要读取,如果不存在,我需要创建一个类)在这种情况下,我将 SQLIgnore 放到幻像类中......这是一个合适的解决方案吗?你怎么看?
【解决方案2】:

我认为您正在寻找的是 XmlDocument。

这是你的第二个任务:

XmlDocument xDoc = new XmlDocument();

xDoc.LoadXml("<root><rates> <permanent votes = \"100\" > 6.54 </permanent>  <temprate votes = \"100\" > 6.54 </temprate></rates> </root> ");

// find the nodes we are interested in
XmlNode Rates = xDoc.SelectSingleNode("//rates");
XmlNode Root = xDoc.SelectSingleNode("root");

// We can't modify a collection live so create a temporary list
List<XmlNode> TempList = new List<XmlNode>();

foreach (XmlNode Node in Rates.ChildNodes)
{
    TempList.Add(Node);          
}

// remove the nodes and their container node
foreach (XmlNode Node in TempList)
{
    Node.ParentNode.RemoveChild(Node);
}
// Use this to remove the parent and children
// in one step
// Rates.ParentNode.RemoveChild(Rates); 

// insert in desired location
foreach (XmlNode Node in TempList)
{
    Root.AppendChild(Node);
}

// Hope this works!
xDoc.Save("C:\\test.xml");

【讨论】:

    猜你喜欢
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多