C# 使用LINQ读取XML并使用格式化
我正在尝试编写一个Linq查询,它将解析我的XML树(实际上是一个解构为XML树的SQL) 我的XML看起来像这样C# 使用LINQ读取XML并使用格式化,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我正在尝试编写一个Linq查询,它将解析我的XML树(实际上是一个解构为XML树的SQL) 我的XML看起来像这样 <SqlRoot> <SqlStatement> <Clause> <OtherKeyword>select</OtherKeyword> <WhiteSpace></WhiteSpace> <Other>t1</Other>
<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>
但它显然失败了,因为我不知道如何考虑空白
节点,并将其转换为实际的空白
。有什么建议吗
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_影响t1
节点:
<WhiteSpace></WhiteSpace>
<Other>bd_orm</Other>
<Period>.</Period>
<Other>dbo</Other>
<Period>.</Period>
<Other>bal_impacts_t</Other>
<WhiteSpace></WhiteSpace>
<Other>t1</Other>
bd_orm
.
dbo
.
平衡影响
t1
您可以在构造查询之前添加空格:
foreach (var ws in xDoc.Descendants("WhiteSpace"))
{
ws.Value = " ";
}
只需为
空白
节点选择一个空格,并为所有其他节点选择字符串值,然后连接结果:
var parts = doc.Descendants("SelectionTarget")
.Elements()
.Select(e => e.Name == "WhiteSpace" ? " " : (string)e);
var text = string.Concat(parts);
var parts = doc.Descendants("SelectionTarget")
.Elements()
.Select(e => e.Name == "WhiteSpace" ? " " : (string)e);
var text = string.Concat(parts);