0

单击按钮后我的代码调用此方法。此方法应在 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>
4

2 回答 2

1

您的外部元素也称为“源”

因此,最后有 2 个“源”端元素。

于 2013-10-08T12:19:56.763 回答
1

问题是根的关闭元素source会导致您打印两次该值。您可以通过为根元素选择不同的名称或更改方法来解决此问题,如下所示:

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 = "";
    }
}
于 2013-10-08T12:22:51.647 回答