解析XML文件时未处理ArgumentException

时间:2013-09-27 20:35:07

标签: c# xml visual-studio-2010 xml-parsing argumentexception

我的目标:我想解析XML文件“REGISTRATION_CATALOGNUMBER” 987654 并将其显示在文本框中。我的XML文件如下所示:

<?xml version="1.0"?>
<!-- This file was generated. -->
<ModificationMap>
<replace>
<!-- Asset Type -->
<text symbol="__HIS_NAME__">Example</text>
<text symbol="__HIS_Example1__">My Program</text>
<text symbol="__HIS_Example2__">EG</text>
<text symbol="__HIS_Example3__">XMLPARSING</text>
<text symbol="__HIS_Example4__">Not Applicable</text>
<text symbol="__HIS_ExampleINTERVAL__">300</text>
</replace>
<replace>
<!-- HIS profile -->
<text symbol="__EG_HIS_NAME__">EG_NotConfigured</text>
<text symbol="__EG_HIS_PASSWORD__">password</text>
<text symbol="__EG_HIS_ExampleINTERVAL__">300</text>
<text symbol="__EG_SERIALNUMBER__">666</text>
</replace>
<replace>
<!-- Changed Number and ID -->
<text symbol="__Example_SERIALNUMBER__">123456789</text>
<text symbol="__REGISTRATION_CATALOGNUMBER__">987654</text>
<text symbol="__HER_ExampleINTERVAL__">300</text>
<text symbol="__HER_LEVEL__">WARN</text>
<text symbol="__Example_VERSION__">20</text>
<text symbol="__Example_THIRDPARTYVERSION__">20</text>
<!-- Asset Profile -->
<text symbol="__HIS_MEMBERNAME__">EG_NotConfigured</text>
<text symbol="__HIS_FRIENDLYNAME__">XMLProgram</text>
<text symbol="__HIS_DESCRIPTION__">testprogram</text>
</replace>
<replace>
<!-- Software director -->
<text symbol="__ADMINUSERNAME__">admin</text>
<text symbol="__ADMINPASSWORD__">password</text>
<text symbol="__HIS_PORT__">0000</text>
<text symbol="__HIS_SCHEME__">http</text>
</replace>
<replace>
<!-- Misc settings -->
<text symbol="__LOG_LEVEL__">ERROR</text>
</replace>
</ModificationMap>

我的代码:

public UserControl1()
{
    InitializeComponent();

    var dict2 = XDocument.Load(@"C:\Users\Smith\Desktop\DEMO.xml")
        .Descendants("text")
        .ToDictionary(f => f.Attribute("symbol").Value, 
        f => f.Value);
    textBox7.Text = dict2["__REGISTRATION_CATALOGNUMBER__"];
}

我收到错误:

  

ArgumentException未处理。具有相同键的项目已经存在   已被添加。

请你能帮助我纠正这个问题吗?谢谢你的帮助!我是c#的新手。 :)

1 个答案:

答案 0 :(得分:1)

您不需要将整个文档解析为Dictionary<string, string>以获得所需的值。请尝试以下方法:

var query = XDocument.Load(@"C:\Users\Smith\Desktop\DEMO.xml")
    .Root.Elements("replace").Elements("text")
    .Where(f => (string)f.Attribute("symbol") == "__REGISTRATION_CATALOGNUMBER__")
    .Select(f => (string)f);
textBox7.Text = query.FirstOrDefault();