从xml中读取字母数字值

时间:2013-08-17 05:28:56

标签: c# xml linq xpath linq-to-xml

根据我的上一个问题 LINQ to XML query returning wrong data

我正在使用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”时,它返回零个房间。我检查了很多次,是否存在使用元素的字母数字值的问题?

1 个答案:

答案 0 :(得分:2)

尝试使用撇号围绕{1}

String.Format(
    "//Department[id={0}]/Section[SectionId='{1}']/Room",
    departmentId,
    sectionId))