How to get the child node by specific attribute value in c#

Spellman.Lau 101 Reputation points
2023-01-12T04:00:55.84+00:00

Hi,

I have a xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>

<gfx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Gfx-ME14.xsd">

    <group name="GroupTrip1" visible="true" wallpaper="false" isReferenceObject="false">

        <text name="TextNo1" caption="1"/>

        <text name="TextEU1" caption="ABcd2/-"/>

        <text name="TextCdt1" caption="&gt;="/>

        <text name="TextTag1" caption="ABCDE-01234"/>

        <ellipse name="EllipseFO1" >

            <animations>

                <animateColor expression="{[Trip_v20]iFO_Idx_01.0}" blinkRate="2">

                    <color value="0" />

                    <color value="1" />

                </animateColor>

            </animations>

        </ellipse>

        <text name="TextDes1" caption="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmn"/>

    </group>

//The other 15 groups, "GroupTrip2","GroupTrip3" ,... ,"GroupTrip16".

</gfx>

I have these code to change caption attribute of the node whose name is TextNo1, 2,...16.

                XmlDocument xmlHMI = new XmlDocument();
                xmlHMI.Load("Z:\\myxml.xml");
                XmlNodeList ndlst = xmlHMI.GetElementsByTagName("group");
                for (int i = 1; i < 17; i++)
                {
                    string strname = "TextNo" + i.ToString();
                    foreach (XmlNode grp in ndlst)
                    {
                        foreach (XmlNode chnd in grp.SelectNodes("text"))
                        {
                            if (chnd.Attributes["name"].Value == strname)
                            {
                                chnd.Attributes["caption"].Value = i.ToString();
                            }
                        }
                    }
                }

It works. But I am wondering what the most efficient way is to do it. Thanks.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-01-12T06:58:05.7433333+00:00

    @Spellman.Lau ,Welcome to Microsoft Q&A, you could try to use XDocument to change caption attribute of the node.

    Here is a code example you could refer to.

     XDocument doc = XDocument.Load("test.xml");
     var result = doc.Descendants("text").Where(i => i.Attributes().Select(m => m.Value.ToString()).FirstOrDefault().Contains("TextNo"));
     int n = 1;
     foreach (var item in result)
     {
       item.Attribute("caption").Value = n.ToString();
       n++;
    }
    doc.Save("test.xml");
    

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our [documentation][3] to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2023-01-12T04:27:04.77+00:00

    Check a variation:

    for( int i = 1; i < 17; i++ )
    {
        foreach( XmlNode n in xmlHMI.SelectNodes( $"/*/group/text[@name='TextNo{i}']" ) )
        {
            n.Attributes["caption"].Value = i.ToString( );
        }
    }
    

    Or maybe:

    foreach( XmlNode n in xmlHMI.SelectNodes( "/*/group/text[starts-with(@name, 'TextNo')]" ) )
    {
        n.Attributes["caption"].Value = n.Attributes["name"].Value.Substring("TextNo".Length);
    }
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.