单击按钮后我的代码调用此方法。此方法应在 MessageBox 键中打印,并在行上显示值。
public static void LoadFromFile()
{
try
{
using (XmlReader xr = XmlReader.Create(@"config.xml"))
{
string sourceValue = "";
string sourceKey = "";
string element = "";
string messageBox = "";
while (xr.Read())
{
if (xr.NodeType == XmlNodeType.Element)
{
element = xr.Name;
if (element == "source")
{
sourceKey = xr.GetAttribute("key");
}
}
else if (xr.NodeType == XmlNodeType.Text)
{
if (element == "value")
{
sourceValue = xr.Value;
}
}
else if ((xr.NodeType == XmlNodeType.EndElement) && (xr.Name == "source"))
{
// there is problem
messageBox += sourceKey + " " + sourceValue + "\n";
}
}
MessageBox.Show(messageBox);
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
方法打印每个键的值正是我想要的。但是最后一个键值方法打印两次。在源 config.xml 中只有 3 个键和 3 个值,但方法打印 4 个键和 4 个值。
这是输出示例:
键 1 我的值 1
键2 myValue2
键3 myValue3
键3 myValue3
另一个例子:
狗汪
猫喵
鸭嘎
鸭嘎
这是我的 XAML 代码:
<?xml version="1.0" encoding="utf-8"?>
<source>
<source key="key1">
<value>myValue1</value>
</source>
<source key="key2">
<value>myValue2</value>
</source>
<source key="key3">
<value>myValue3</value>
</source>
</source>