【问题标题】:Read XML using LINQ using formatting使用 LINQ 使用格式化读取 XML
【发布时间】:2015-06-11 15:10:10
【问题描述】:

我正在尝试编写一个 Linq 查询来解析我的 XML 树(它实际上是一个被解构为 XML 树的 SQL)。

我的 XML 看起来像这样

<SqlRoot>
  <SqlStatement>
    <Clause>
      <OtherKeyword>select</OtherKeyword>
      <WhiteSpace></WhiteSpace>
      <Other>t1</Other>
      <Period>.</Period>
      <Other>empid</Other>
      <WhiteSpace></WhiteSpace>
    </Clause>
    <Clause>
      <OtherKeyword>from</OtherKeyword>
      <SelectionTarget>
        <WhiteSpace></WhiteSpace>
        <Other>bd_orm</Other>
        <Period>.</Period>
        <Other>dbo</Other>
        <Period>.</Period>
        <Other>bal_impacts_t</Other>
        <WhiteSpace></WhiteSpace>
        <Other>t1</Other>
      </SelectionTarget>
    </Clause>
  </SqlStatement>
</SqlRoot>

我正在尝试挑选表名(SelectionTarget 节点)。 WhiteSpace 节点是值之间的空白/空白。

所以我期望的输出类似于bd_orm.dbo.bal_impacts_t t1,但我无法通过在两者之间添加whitespace 来弄清楚如何做到这一点。

我试过了

 var xxx = (from res in xDoc.Descendants("Clause").Descendants("SelectionTarget") select res);

Console.WriteLine(xxx.DescendantNodesAndSelf().OfType<XElement>().First().Value);

但它显然失败了,因为我不知道如何考虑whitespace 节点并将其转换为实际的whitespace。有什么建议吗?

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:

    只需为WhiteSpace 节点选择一个空格,为所有其他节点选择字符串值,然后连接结果:

    var parts = doc.Descendants("SelectionTarget")
        .Elements()
        .Select(e => e.Name == "WhiteSpace" ? " " : (string)e);
    
    var text = string.Concat(parts);
    

    【讨论】:

      【解决方案2】:
      var nodes = (from res in xDoc.Descendants("Clause")
                                   .Descendants("SelectionTarget")
                                   .Descendants() 
                   select res);
      string name = String.Join("", nodes.Select(n=>n.Name == "WhiteSpace"?" ":n.Value));
      

      姓名:bd_orm.dbo.bal_impacts_t t1

      demo

      节点:

      <WhiteSpace></WhiteSpace>
      <Other>bd_orm</Other>
      <Period>.</Period>
      <Other>dbo</Other>
      <Period>.</Period>
      <Other>bal_impacts_t</Other>
      <WhiteSpace></WhiteSpace>
      <Other>t1</Other>
      

      【讨论】:

        【解决方案3】:

        您可以在构造查询之前添加空格:

         foreach (var ws in xDoc.Descendants("WhiteSpace"))
         {
              ws.Value = " ";
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-08
          相关资源
          最近更新 更多