简体   繁体   中英

create if statements blocks based on the value of an XML element

How can i create if statements blocks based on the value of id (XML element)

string filepath = Server.MapPath("XMLFile2.xml");

XmlDocument xdoc1 = new XmlDocument();
xdoc1.Load(filepath);

XmlNode root = xdoc1.DocumentElement;
XmlNode idNode = root.SelectSingleNode("/students/student/id");

   if (idNode.Value == 1.ToString()){my code}

im afraid that this code selects the first node in the file,,, or this there another way i can select the node based on its id value????

Replace your this code

Previous code

XmlNode idNode = root.SelectSingleNode("/students/student/id");

New code

XmlNode idNode = root.SelectSingleNode("//students/student/id");

And ya mostly if you want to search node base on the value of id than use following.

XmlNode idNode = root.SelectSingleNode("//students/student/[id='"+<YOUR id>+"']");

It will work...

You can use LINQ2XML

XElement doc =XElement.Load(filepath);
var xpath = String.Format("//students/student/[id='{0}']", "1");
                                                            -
                                                            |->your ID value goes here
var StudentNodeWithID1= doc.XPathSelectElement(xpath);
//selects a single student node with id as 1 or would return NULL if there are no students with id as 1

OR

var StudentNodeWithID1= doc.Elements("student")
                           .Where(s => s.Element("id").Value == "1")
                           .SingleOrDefault();

StudentNodeWithID1.Element("id");//id node
StudentNodeWithID1.Element("id").Value;//id 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