I'm using XPathSelectElement to store data into an XML file. How can I in the code snippet below use a global variable name instead of id name 'City1'?
I want the code to be:
string myVariable = "City1"
XElement fname= country.XPathSelectElement("country/city/major[@id = myVariable]/firstname");
Thank you for your help
This is my XML:
<country>
  <city>
    <cityname>City1</cityname>
    <citynr>111</citynr>
    <person>
      <name>Person1</name>
      <name>Person2</name>
      <name>Person3</name>
      <name>Person4</name>
    </person>
    <major id=City1>
      <firstname>Major1firstname</firstname>
      <lastname>Major1lastname</lastname>
    </major>
  </city>
  <city>
    <cityname>City2</cityname>
    <citynr>222</citynr>
    <person>
      <name>Person5</name>
      <name>Person6</name>
      <name>Person7</name>
      <name>Person8</name>
    </person>
    <major id=City2>
      <firstname>Major2firstname</firstname>
      <lastname>Major2firstname</lastname>
    </major>
  </city>
</country>
Here is my code:
XDocument country= XDocument.Load(Server.MapPath("myXML.xml"));
XElement fname= country.XPathSelectElement("country/city/major[@id = 'City1']/firstname");
XElement lname= country.XPathSelectElement("country/city/major[@id = 'City1']/lastname");
fname.Value = firstname.Text;
lname.Value = lastname.Text;
country.Save(Server.MapPath("myXML.xml"));
 
  
                     
                        
I'd just use the selection methods within LINQ to XML instead:
XElement fname = country.Element("country")
                        .Elements("city")
                        .Elements("major")
                        .Where(x => (string) x.Attribute("id") == myVariable)
                        .Elements("firstname")
                        .FirstOrDefault();
(By using FirstOrDefault, the result will be null if no such element is found.)
 
                    See more on this question at Stackoverflow