从xml

时间:2015-12-04 13:08:05

标签: c# xml linq

我有那个xml文件

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
  <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
    bla bla bla
  </DocumentProperties>
  <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
    <AllowPNG/>
  </OfficeDocumentSettings>
  <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    <SupBook>
      <Path>text</Path>
      <SheetName>text</SheetName>
      <SheetName>text</SheetName>
      <SheetName>cancellation</SheetName>
      <SheetName>text</SheetName>
      <SheetName>Pivot</SheetName>
      <SheetName>list</SheetName>
      <SheetName>text</SheetName>
      <Xct>
        <Count>5173</Count>
        <SheetIndex>0</SheetIndex>
        <Crn>
          <Row>0</Row>
          <ColFirst>1</ColFirst>
          <ColLast>9</ColLast>
          <Text>text</Text>
          <Text>text</Text>
          <Text>text</Text>
          <Number>0</Number>
          <Text>text</Text>
          <Number>0</Number>
          <Number>0</Number>
          <Number>0</Number>
          <Number>0</Number>
        </Crn>
        <Crn>
          <Row>1</Row>
          <ColFirst>1</ColFirst>
          <ColLast>5</ColLast>
          <Number>49</Number>
          <Text>text</Text>
          <Text>text</Text>
          <Number>0</Number>
          <Text>text</Text>
        </Crn>
   </ExcelWorkbook>
</Workbook>

它包含很多大的xml代码(大约5000)。我正在尝试从TEXT中选择Crn个元素。我怎样才能做到这一点?

我正在尝试这个:

IEnumerable<string> ss = from q in XDocument.Load(path).Descendants("Crn")                                                          
select q.Element("Text").Value;

            foreach (var x in ss)
            {
                Console.WriteLine(x);
            }

但这没有任何价值

1 个答案:

答案 0 :(得分:1)

在查询时,您需要添加与XML关联的命名空间。这将为您提供预期的输出: -

 XNamespace ns = "urn:schemas-microsoft-com:office:excel";
 IEnumerable<string> ss = xdoc.Descendants(ns + "Crn")
                              .Elements(ns + "Text")
                              .Select(x => (string)x);