[英]XML Element's element/attribute annotation in C#
是否可以通過不帶幻象類的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解析器?
無法獲得根類的“一個子元素及其屬性”,而僅通過 XML序列化屬性將其轉換為XML序列化過程中其根類的元素。
但是,您可以通過以下方式歸檔所需的結果:
我認為您正在尋找的是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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.