我正在使用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"));
答案 0 :(得分:3)
我只是在LINQ to XML中使用选择方法:
XElement fname = country.Element("country")
.Elements("city")
.Elements("major")
.Where(x => (string) x.Attribute("id") == myVariable)
.Elements("firstname")
.FirstOrDefault();
(使用FirstOrDefault
,如果找不到此类元素,结果将为null
。)
答案 1 :(得分:1)
您可以使用:
var fname = country
.XPathSelectElement(
"//country/city/major[@id = '" + myVariable + "']/firstname");
或
var fname = country
.XPathSelectElement(
String.Format("//country/city/major[@id = '{0}']/firstname", myVariable));
我相信,在下面的评论中,@ Tomalak提到的缓解XPath注入的一种方法是使用XName
类型而不是字符串(异常处理范围外的异常处理):
XName myVariable = "City1";
答案 2 :(得分:0)
您要么正在寻找string.Format
,要么正在寻找StringBuilder
类。
fname= country.XPathSelectElement(string.Format("country/city/major[@id = '{0}']/firstname",myVariable));
的引用:
http://msdn.microsoft.com/de-de/library/fht0f5be(v=vs.85).aspx
http://msdn.microsoft.com/de-de/library/2839d5h5(v=vs.90).aspx