繁体   English   中英

LINQ to XML新手问题

[英]LINQ to XML Newbie Question

我已加载具有以下结构的XML文档:

<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <sheetData>
    <row r="1" spans="1:2">
      <c r="A1" t="s">
        <v>0</v>
      </c>
      <c r="B1" t="s">
        <v>1</v>
      </c>
    </row>
  </sheetData>
</worksheet>

我想查询文档中所有名为t = s的属性c元素。

我已经尝试了许多不同的方法来做到这一点:

XDocument xmlDoc = XDocument.Load(@"..\..\Sheet1.xml");
var rows = from row in xmlDoc.Root.Descendants("worksheet").Elements("sheetData")
       select row;

但是它总是返回一个空集。

我想念什么?

您需要指定使用后代或元素获取的节点的名称空间。

XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var rows = from row in xmlDoc.Root.Descendants(ns + "sheetData")
       select row;

Root元素是<worksheet/>元素,因此向根请求工作表后代将始终返回一个空集。 删除.Descendants("worksheet")子句,您应该开始看到一些结果。

这是我在Linqpad中编写的一些代码,该代码在t = s的c上进行过滤。

我知道答案已经被接受,但是此解决方案实际上会进行过滤,而上述其他答案都没有:)

希望这可以帮助!

void Main()
{
    var xml = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
        <worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">
            <sheetData>
                <row r=""1"" spans=""1:2"">
                    <c r=""A1"" t=""s"">
                        <v>0</v>
                    </c>
                    <c r=""A2"" t=""b"">
                        <v>0</v>
                    </c>
                    <c r=""B1"" t=""s"">
                        <v>1</v>
                    </c>
                </row>
            </sheetData>
        </worksheet>";

    XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

    var d = XDocument.Parse(xml);
    //d.Dump();
    //d.Dump("xdocument dump");

    var q = from cell in d.Root.Descendants(ns + "sheetData").Descendants(ns + "row").Descendants(ns + "c")
            where cell.Attributes("t").FirstOrDefault().Value == "s"
            select cell;
    q.ToList().Dump();

}

XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
XDocument xmlDoc = XDocument.Load(@"..\..\Sheet1.xml");
var rows = from row in xmlDoc.Root.Element(ns + "sheetData").Elements(ns + "row")
       select row;

这将从root / sheetData元素中获取所有“行”元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM