C# XAML读卡器重复打印
我的代码在单击按钮后调用此方法。此方法应在MessageBox中打印带有行上值的键C# XAML读卡器重复打印,c#,wpf,xaml,C#,Wpf,Xaml,我的代码在单击按钮后调用此方法。此方法应在MessageBox中打印带有行上值的键 public static void LoadFromFile() { try { using (XmlReader xr = XmlReader.Create(@"config.xml")) { string sourceValue = ""; string sourceKey = ""; s
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);
}
}
方法以我想要的值打印每个键但带值方法的最后一个键打印两次。在source config.xml中只有3个键和3个值,但该方法打印4个键和4个值
这是输出的示例:
键1 myValue1
键2 myValue2
key3 myValue3
key3 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>
myValue1
myValue2
myValue3
您的外部元素也称为“源”
因此,在末尾有两个“源”端元素
问题在于,根
源的结束元素导致您打印两次值。您可以通过为根元素选择其他名称或通过如下更改方法来解决此问题:
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 (sourceValue != "" && (xr.NodeType == XmlNodeType.EndElement) && (xr.Name == "source"))
{
// there is problem
messageBox += sourceKey + " " + sourceValue + "\n";
sourceValue = "";
}
}
你能添加你的XAML吗?@EliArbel我的问题更新了。