如何使用未关闭的标签处理XML?

时间:2014-08-15 08:47:43

标签: c# xml

我有以下Xml文件

<?xml version="1.0" encoding="UTF-8"?>
<session xmlns="http://winscp.net/schema/session/1.0" name="test" start="2014-04-04T15:54:09.728Z">
  <upload>
    <filename value="D:\ftp\test1.TXT" />
    <destination value="/in/test1.TXT" />
    <result success="true" />
  </upload>
  <touch>
    <filename value="/in/test1.TXT" />
    <modification value="2014-03-27T12:45:20.000Z" />
    <result success="true" />
  <upload>
    <filename value="D:\ftp\test2.TXT" />
    <destination value="/in/test2.TXT" />
    <result success="true" />
  </upload>
  <touch>
    <filename value="/in/test2.TXT" />
    <modification value="2014-03-27T12:45:20.000Z" />
    <result success="false" />
  </touch>
</session>

我想浏览所有文件名元素,其中result success =“true”表示触摸和上传两个节点。

我写了以下代码

 var upload = from el in root.Elements("upload") select el;
  var touch = from el in root.Elements("touch") select el;

  // use zip to join the two lists together based on ordering to a new object
  // this WON'T work if the lists are different lengths!
  var filename = upload.Zip(touch,(u,t) => new { upload = u, touch = t })
        .Where(item => item.upload.Descendants("result").First().Attribute("success").Value  == "true" 
                   &&  item.touch.Descendants("result").First().Attribute("success").Value  == "true")
        .Select(item => item.upload.Descendants("filename").First().Attribute("value").Value);

它工作正常但我的问题有时候我用uclosed标签读取xml: 例如

<?xml version="1.0" encoding="UTF-8"?>
    <session xmlns="http://winscp.net/schema/session/1.0" name="test" start="2014-04-04T15:54:09.728Z">
      <upload>
        <filename value="D:\ftp\test1.TXT" />
        <destination value="/in/test1.TXT" />
        <result success="true" />
      </upload>
      <touch>
        <filename value="/in/test1.TXT" />
        <modification value="2014-03-27T12:45:20.000Z" />
        <result success="true" />
      <upload>
        <filename value="D:\ftp\test2.TXT" />
        <destination value="/in/test2.TXT" />
        <result success="true" />

在这种情况下,上面的代码不起作用,如何更改它以便读取带有未闭合标签的xml文件?

非常感谢,任何帮助都将是最受欢迎的!

1 个答案:

答案 0 :(得分:0)

您不能,因为除非xml有效,否则集合无效。考虑在针对它运行此代码之前验证xml。