0

我的目标:我想解析987654的“REGISTRATION_CATALOGNUMBER”的 XML 文件并将其显示在文本框中。我的 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# 的新手。:)

4

1 回答 1

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();
于 2013-09-27T20:43:04.603 回答