1

我正在使用 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"));
4

3 回答 3

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如果没有找到这样的元素。)

于 2013-10-31T07:23:50.987 回答
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";
于 2013-10-31T07:24:23.807 回答
0

您正在寻找string.FormatStringBuilder上课。

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

于 2013-10-31T07:24:21.447 回答