简体   繁体   English

使用格式化使用 LINQ 读取 XML

[英]Read XML using LINQ using formatting

I am trying to write a Linq query which will parse my XML tree(which is actually a SQL deconstructed into an XML tree).我正在尝试编写一个 Linq 查询来解析我的 XML 树(它实际上是一个 SQL 解构成一个 XML 树)。

My XML looks like this我的 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>

I am trying to pick out the table name ( SelectionTarget node).我试图找出表名( SelectionTarget节点)。 The WhiteSpace node is a blank/white space in between the values. WhiteSpace节点是值之间的空白/空白区域。

So the output which I expect is something like this bd_orm.dbo.bal_impacts_t t1 but I am unable to figure out how to do this by including a whitespace in between.所以我期望的输出类似于bd_orm.dbo.bal_impacts_t t1但我无法弄清楚如何通过在它们之间包含一个whitespace来做到这一点。

I tried this我试过这个

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

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

but it obviously fail cause I do not know how to take into account the whitespace node and convert that into an actual whitespace .但它显然失败了,因为我不知道如何考虑whitespace节点并将其转换为实际的whitespace Any suggestions?有什么建议?

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));

name: bd_orm.dbo.bal_impacts_t t1名称: bd_orm.dbo.bal_impacts_t t1

demo演示

nodes:节点:

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

Simply select a space for the WhiteSpace nodes and the string value for all other nodes, then concatenate the results:只需为WhiteSpace节点选择一个空格,为所有其他节点选择字符串值,然后连接结果:

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

var text = string.Concat(parts);

You could add the whitespace before constructing the query:您可以在构造查询之前添加空格:

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

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

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