XDocument.Parse之后的后代命令在c#WP8中返回NULL

时间:2014-03-26 09:08:24

标签: c# xml windows-phone-8 xml-parsing

我有一个文件,我从隔离存储打开。我得到的是一个字符串类型的XML。 我需要解析XML以获取特定的字段内容,但是有一些问题。

我尝试使用XDocument.Parse并获得了XML,然后我使用了Descendants并编写了我需要的节点的名称,但是在调试它时 - 我看到了返回的值是NULL。

有人可以告诉我,我做错了什么吗?

IsolatedStorageFileStream file = storage.OpenFile(txtFilePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(file))
   {
     //message += reader.ReadToEnd();
      message = reader.ReadToEnd();
   }
  var doc = XDocument.Parse(message);
  var res = doc.Descendants("value").Select(o => o.Value).ToArray();
  // res is NULL
  var x = res[0];
  message = x;

这是XML文档,我需要的唯一内容是节点<value>下的ine(第三行)

    <xsi:document xmlns="@link" xmlns:xsi="@link" xsi:schemaLocation="@link" version="1.0">
        <xsi:field left="51" top="235" right="224" bottom="280" type="text">
        <xsi:value encoding="utf-16">| amount: 152.467</xsi:value>
        <xsi:line left="52" top="245" right="179" bottom="267">
        <xsi:char left="52" top="245" right="55" bottom="267" confidence="93">|</xsi:char>
        <xsi:char left="56" top="245" right="78" bottom="267" confidence="100"></xsi:char>
        <xsi:char left="79" top="254" right="84" bottom="261" confidence="43">a</xsi:char>
        <xsi:char left="86" top="254" right="96" bottom="261" confidence="100">m</xsi:char>
        <xsi:char left="98" top="254" right="105" bottom="261" confidence="94">o</xsi:char>
        <xsi:char left="106" top="254" right="112" bottom="261" confidence="31">u</xsi:char>
        <xsi:char left="114" top="254" right="120" bottom="261" confidence="34">n</xsi:char>
        <xsi:char left="121" top="252" right="126" bottom="261" confidence="59">t</xsi:char>
        <xsi:char left="127" top="254" right="129" bottom="261" confidence="76">:</xsi:char>
        <xsi:char left="130" top="252" right="133" bottom="261" confidence="100"></xsi:char>
        <xsi:char left="134" top="252" right="140" bottom="261" confidence="100">1</xsi:char>
         <xsi:char left="141" top="252" right="147" bottom="261" confidence="100">5</xsi:char>
        <xsi:char left="148" top="252" right="154" bottom="261" confidence="55">2</xsi:char>
        <xsi:char left="155" top="259" right="157" bottom="261" confidence="100" suspicious="true">.</xsi:char>
        <xsi:char left="158" top="252" right="165" bottom="261" confidence="71">4</xsi:char>
        <xsi:char left="166" top="252" right="172" bottom="261" confidence="40">6</xsi:char>
        <xsi:char left="173" top="252" right="179" bottom="261" confidence="100">7</xsi:char>
       </xsi:line>
     </xsi:field>
   </xsi:document>

2 个答案:

答案 0 :(得分:1)

问题是名称空间xsi。首先,声明它

XNamespace xsi = "...";

然后将您的LINQ查询更改为

var res = doc.Descendants(xsi+"value").Select(o => o.Value).ToArray();

答案 1 :(得分:0)

除了@ Igor的回答,你需要把XML命名空间指向的URI:

xmlns:xsi="@link"

作为XNamespace变量的值:

XNamespace xsi = "@link";
var res = doc.Descendants(xsi+"value").Select(o => o.Value).ToArray();