1

根据我的最后一个问题 LINQ to XML 查询返回错误数据

我正在使用 XPath 以下列方式阅读此 XML

<?xml version="1.0" encoding="utf-8" ?>
<Departments>
  <Department>
    <id>001</id>
    <Section>
      <SectionId>001001</SectionId>
      <Room>
        <RoomID>001001001</RoomID>
        <Owner>guest1</Owner>
      </Room>
      <Room>
        <RoomID>001001002</RoomID>
        <Owner>guest11</Owner>
      </Room>
    </Section>
    <Section>
      <SectionId>001002</SectionId>
      <Room>
        <RoomID>001002001</RoomID>
        <Owner>guest2</Owner>
      </Room>
    </Section>
  </Department>
</Departments>

阅读代码是

 string  departmentId = "001", sectionId = "001001";
 var xDoc = XDocument.Load(inputUrl);
 var rooms = xDoc.XPathSelectElements(
 String.Format(
    "//Department[id={0}]/Section[SectionId={1}]/Room",
    departmentId,
    sectionId))
.Select(el => new Room
 {
    roomID = (string)el.Element("RoomID"),
    owner = (string)el.Element("Owner")
}).ToList(); 

但是当我在xml和代码中将sectionId更改为字符串“str1234”时,它返回零个房间。我检查了很多次,使用元素的字母数字值有问题吗?

4

1 回答 1

2

Try surrounding the {1} with apostrophes:

String.Format(
    "//Department[id={0}]/Section[SectionId='{1}']/Room",
    departmentId,
    sectionId))
于 2013-08-17T06:43:04.320 回答