简体   繁体   中英

C# Parse XML & action if attribute of node matches a string

So I'm currently trying to parse an existing XML file in a WPF application, and upon doing so check a certain node's attributes to see if it matches to a string.

My code is currently as follows:

public static void ParseExistingKingdomXML()
    {
        XmlDocument ParseExistingKingdomXML_xDoc = new XmlDocument();
        ParseExistingKingdomXML_xDoc.Load(XMLExistingKingdomsStrings.ExistingKingdomsXMLFile);

        foreach (XmlNode node in ParseExistingKingdomXML_xDoc.DocumentElement)
        {
            if (node.Name == "Kingdom")
            {
                var attribute = node.Attributes["title"].ToString();
                if (attribute == XMLExistingKingdomsStrings.KingdomName) {
                    XMLExistingKingdomsStrings.KingdomID = node.Attributes["title"].Value;
                }
            }
        }
    }

Later in my progam I try to just return the string KingdomID to a text box, however it is currently just returning null.

My XML file example:

https://hastebin.com/fuxehaqeha.xml

In principle if the title value matches a pre-defined string (based off which TreeNode a user clicks on) I want to run a load of code.

You misunderstood the attribute ToString() function. The way you do it you are comparing the string of the class name "System.Xml.XmlAttribute" instead of the actual value you wanted. So assuming all of your other code works this should work

    foreach (XmlNode node in ParseExistingKingdomXML_xDoc.DocumentElement)
    {
        if (node.Name == "Kingdom")
        {
            var attribute = node.Attributes["title"].Value;
            if (attribute == XMLExistingKingdomsStrings.KingdomName) {
                XMLExistingKingdomsStrings.KingdomID = node.Attributes["title"].Value;
            }
        }
    }
    

It is better to use LINQ to XML API. It is available for more than a decade in the.Net framework.

The code below shows how to get any attribute of the <Kingdom> element. After that you can apply any logic you need.

c#

void Main()
{

    //XDocument xdoc = XDocument.Load(@"fileName");
    
    XDocument xdoc = XDocument.Parse(@"<?xml version='1.0' encoding='utf-8'?>
        <Kingdoms>
            <!--kingdom factions-->
            <Kingdom id='empire' owner='Hero.lord_1_1'
                     banner_key='11.4.4.4345.4345.768.768.1.0.0.163.0.5.512.512.769.764.1.0.0'
                     primary_banner_color='0xff793191'
                     secondary_banner_color='0xffFCDE90' label_color='FF850C6D'
                     color='FF4E3A55' color2='FFDE9953' alternative_color='FFffffff'
                     alternative_color2='FF660653' culture='Culture.empire'
                     settlement_banner_mesh='encounter_flag_a'
                     flag_mesh='info_screen_flags_b' name='{=NF627oiX}Northern Empire'
                     short_name='{=nsDj8Qxl}northern Empire'
                     title='{=NF627oiX}Northern Empire' ruler_title='{=8pjMAqOg}Senate'
                     text='{=fE5U9ApA}The Calradian Empire is not a monarchy. The Calradians insist on this. The emperor, formerly just a military commander, may have taken on most other affairs of state as well. Rather than be elected every few years by the Senate, he may now rule for life and often be succeeded by his son. The popular assemblies that once decided key policies may have withered away, and the Senate, a gathering of landowners, may have far less power than it did in centuries pass. But it is not a monarchy, because it is absolutely forbidden for Calradians to be ruled by a king. The Empire is what happens when a league of city-states conquers a continent. A community once led by free farmers with relatively equal wealth now has vast gaps between the rich and the poor. Institutions designed to prevent one man from becoming a tyrant come into conflict with the necessities of unending warfare, which require unified command. Without any smooth means of succession, the death of an emperor has always been a potential crisis. Usually, the emperor nominated an heir, the senate ratified his choice, and the people (meaning the army) acclaimed it. But this did not always happen smoothly, and then the succession was settled on the battlefield. The current conflict, which broke out when the late Emperor Arenicos died mysteriously, is the latest of these imperial civil war.'>
                <relationships>
                    <relationship kingdom='Kingdom.khuzait' value='-1' isAtWar='true'/>
                </relationships>
                <policies>
                    <policy id='policy_senate'/>
                    <policy id='policy_feudal_inheritance'/>
                </policies>
            </Kingdom>
        </Kingdoms>");

    string title = xdoc.Root.Element("Kingdom").Attribute("title")?.Value;
    string short_name = xdoc.Root.Element("Kingdom").Attribute("short_name")?.Value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM