문제

My Goal: I want to parse XML file for "REGISTRATION_CATALOGNUMBER" which is 987654 and display it in a textbox. My XML file looks like this:

<?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>

My Code:

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__"];
}

I am getting an Error:

ArgumentException was unhandled. An item with the same key has already been added.

Please can you help me rectify the problem? Thanks for your help! I am new to c#. :)

도움이 되었습니까?

해결책

You don't need whole document parsed to Dictionary<string, string> to get the value you need. Try following:

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top