繁体   English   中英

C# 如果节点的属性与字符串匹配,则解析 XML & 操作

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

因此,我目前正在尝试在 WPF 应用程序中解析现有的 XML 文件,并在这样做时检查某个节点的属性以查看它是否与字符串匹配。

我的代码目前如下:

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;
                }
            }
        }
    }

稍后在我的程序中,我尝试将字符串 KingdomID 返回到文本框,但它目前只是返回 null。

我的 XML 文件示例:

https://hastebin.com/fuxehaqeha.xml

原则上,如果标题值与预定义的字符串匹配(基于用户单击的 TreeNode),我想运行大量代码。

您误解了属性ToString() function。 您这样做的方式是比较 class 名称“System.Xml.XmlAttribute”的字符串,而不是您想要的实际值。 因此,假设您所有其他代码都有效,这应该有效

    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;
            }
        }
    }
    

最好使用LINQ 到 XML API。 它在 .Net 框架中可用了十多年。

下面的代码显示了如何获取<Kingdom>元素的任何属性。 之后,您可以应用您需要的任何逻辑。

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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