我正在嘗試將值反序列化為 aXmlAttribute或 a XmlTextfor equal xml 標簽。
反序列化時,兩個選項都應該有效,并且兩個選項最終都應該將值反序列化為類的同一個屬性。
基本上我的 xml 看起來像這樣:
<ArrayTest>
<ArrayItem>Item1</ArrayItem>
<ArrayItem Value="Item2"/>
</ArrayTest>
并給出了課程:
public class ArrayTest
{
[XmlElement(nameof(ArrayItem))]
public ArrayItem[] Items { get; set; }
}
public class ArrayItem
{
//[XmlAttribute]
//[XmlText]
public string Value { get; set; }
}
我希望“Item1”和“Item2”最終出現在相應 ArrayItems 的 Value 屬性中。
我知道這樣的事情是在 xaml 中為 WPF 完成的,例如在定義TextTextBlock的屬性時,我可以在 xml 標簽中以及直接在 Text 屬性中設定它。IE
<TextBlock Text="Sample text"/>
<TextBlock>
Sample Text
<TextBlock/>
我已經嘗試了相應類屬性的不同組合,但似乎最后一個最終會覆寫前一個,所以我只剩下兩個選項之一。
此外,如果可以使用XmlSerializer類,我會更喜歡。
編輯: 受Auditive回答的啟發,我采用了以下方法:
public class ArrayItem
{
[XmlAttribute(nameof(Value))]
public string ValueAttribute
{
get => mValue;
set => mValue = value;
}
[XmlText]
public string Value
{
get => mValue;
set => mValue = value;
}
private string mValue;
}
這適用于我的情況。
但是請注意,這不適用于序列化,因為這樣可以保存兩個屬性。
uj5u.com熱心網友回復:
為什么你不會為節點值和屬性值使用分開的屬性?
public class ArrayItem
{
[XmlAttribute("Value")]
public string ValueAttribute { get; set; }
[XmlText]
public string Value { get; set; }
}
通過這個例子:
static void Main(string[] args)
{
ArrayTest arrayTest = new ArrayTest
{
Items = new ArrayItem[]
{
new ArrayItem{ Value = "Item1" },
new ArrayItem{ ValueAttribute = "Item2" }
}
};
XmlSerializer serializer = new XmlSerializer(typeof(ArrayTest));
using FileStream fs = new FileStream("MyFile.xml", FileMode.OpenOrCreate);
serializer.Serialize(fs, arrayTest);
}
它將為您提供所需的輸出:
<?xml version="1.0"?>
<ArrayTest>
<ArrayItem>Item1</ArrayItem>
<ArrayItem Value="Item2" />
</ArrayTest>
從檔案反序列化也可以正常作業:
using (FileStream fs = new FileStream("H:\\MyFile2.xml", FileMode.OpenOrCreate))
{
ArrayTest deserializedArrayTest = formatter.Deserialize(fs) as ArrayTest;
foreach (ArrayItem arrayItem in deserializedArrayTest.Items)
Console.WriteLine("Array item value: " arrayItem.Value "\n"
"Array \"Value\" attribute value: " arrayItem.ValueAttribute);
}

我認為這種方法和相同的命名遲早會誤導你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/316688.html
