使用C#和VS2008将linq转换为xml

时间:2009-05-28 14:44:29

标签: c# .net xml linq

XML格式化

<status>
 <webresponse>
  <properties>
   <props>
    <imghandle>
     <image handle=1234>
      <imagetag>somewhere</imagetag>
     </image>
    </imghandle>
   </props>
   <props>
    <imghandle>
     <image handle=1235>
      <imagetag>somewhere1</imagetag>
     </image>
    </imghandle>
   </props>
  </properties>
 </webresponse>
</status>

以上是第三方回复给我的xml样本。我正在尝试使用Linq到XMl来构建我的对象,我正试图导航到<imghandle>/<image handle=1234>。我可以用Xpath做到但是当我做以下操作时,我得到对象引用没有设置错误

from c in searchXMLResult.Descendants("props")
select c.Element("imghandle").Element("image").Attribute("handle");

PS:我知道我的xml格式不是为了便于阅读,在这里提问时如何放置XML部分?

更新1: 所以在经历了第三方的烦恼之后,我终于得到了一个答案,说我正在消耗的数据已经过时,他们给了我新的格式化数据,看起来像这样

<status>
     <webresponse>
      <properties>
       <props>
        <imghandle>
         <image handle="1234">
          <imagetag>somewhere</imagetag>
         </image>
        </imghandle>
        <owner>
          <image handle="ABcf">
          </image>
        </owner>
       </props>
       </properties>
     </webresponse>
    </status>

我尝试了Kevin Thige的建议,看看下面的用户建议,我得到一个对象引用错误。不能在2个不同的部分下使用相同的元素不能与Linq一起使用XML吗?即

from c in searchXMLResult.Descendants("props")

选择c.Element(“imghandle”)。元素(“图像”)。属性(“句柄”);

和/或

from c in searchXMLResult.Descendants("props")

选择c.Element(“所有者”)。元素(“图像”)。属性(“句柄”)

UPDATE2: 这是我获取并保存到磁盘的xml

<?xml version="1.0" encoding="utf-8"?>
<status>
  <webresponse>
    <properties>
      <props>
        <imghandle>
          <image handle="537">
            <imagetag>SFO</imagetag>
          </image>
        </imghandle>
        <owner>
          <image handle="User-2">
            <firstname>
            </firstname>
            <lastname>Site Administrator</lastname>
            <username>admin</username>
          </image>
        </owner>
        <creationdate>2009-03-06T18:07:57Z</creationdate>
        <summary>
        </summary>
      </props>
      <status>HTTP/1.1 200 OK</status>
    </properties>
  </webresponse>
</status>

1 个答案:

答案 0 :(得分:2)

下面的代码对我有用,一旦我在'handle'属性值周围加上引号:

XDocument xdoc = XDocument.Parse(@"
<status>
 <webresponse>
  <properties>
   <props>
    <imghandle>
     <image handle='1234'>
      <imagetag>somewhere</imagetag>
     </image>
    </imghandle>
   </props>
   <props>
    <imghandle>
     <image handle='1235'>
      <imagetag>somewhere1</imagetag>
     </image>
    </imghandle>
   </props>
  </properties>
 </webresponse>
</status>
");

var v = from c in xdoc.Descendants("props")
select c.Element("imghandle").Element("image").Attribute("handle");

编辑:如果不修改输入以使xml有效,我不知道你可以用XDocument或XmlDocument对象做什么。如果您尝试加载无效的xml,则两者都会抛出异常。

EDIT2:第二个xml示例仍无效:(。标记<image handle='ABcf'>未关闭。