我正在使用 XPathSelectElement 将数据存储到 XML 文件中。如何在下面的代码片段中使用全局变量名称而不是 id 名称“City1”?
我希望代码是:
string myVariable = "City1"
XElement fname= country.XPathSelectElement("country/city/major[@id = myVariable]/firstname");
谢谢您的帮助
这是我的 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>
这是我的代码:
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"));