提问人:Basava 提问时间:1/12/2023 最后编辑:dbcBasava 更新时间:1/19/2023 访问量:58
如何在 C 中将 Parent 元素和 Child 元素与 “ : ” (冒号) 合并#
How to merge Parent Element and Child element with " : " (colon) in C#
问:
输入 Xml:
<title>Discourse interaction between <italic>The New York Times</italic> and <italic>China Daily</italic></title> <subtitle>The case of Google's departure</subtitle>
所需输出:
Discourse interaction between The New York Times and China Daily: The case of Google's departure
我的代码:
String x = xml.Element("title").Value.Trim();
现在我得到:
Discourse interaction between The New York Times and China Daily:
答:
0赞
dbc
1/19/2023
#1
<subtitle>
不是 的子元素,而是同级元素。您可以通过使用缩进格式化包含元素来查看这一点:<title>
xml
<someOuterElementNotShown>
<title>Discourse interaction between <italic>The New York Times</italic> and <italic>China Daily</italic></title>
<subtitle>The case of Google's departure</subtitle>
</someOuterElementNotShown>
若要获取给定元素后面的同级元素,请使用 ElementsAfterSelf():
var title = xml.Element("title"); // Add some null check here?
var subtitles = string.Concat(title.ElementsAfterSelf().TakeWhile(e => e.Name == "subtitle").Select(e => e.Value)).Trim();
var x = subtitles.Length > 0 ? string.Format("{0}: {1}", title.Value.Trim(), subtitles) : xml.Value.Trim();
评论