[英]How to merge Parent Element and Child element with " : " (colon) in C#
Input Xml:输入 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>
Required Output:必填 Output:
Discourse interaction between The New York Times and China Daily: The case of Google's departure
My code:我的代码:
String x = xml.Element("title").Value.Trim();
Now I am getting:现在我得到:
Discourse interaction between The New York Times and China Daily:
<subtitle>
is not a child element of <title>
, it is a sibling element . <subtitle>
不是<title>
的子元素,它是兄弟元素。 You can see this by formatting your containing element xml
with indentation:您可以通过使用缩进格式化包含元素
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>
To get the sibling elements following a given element, use ElementsAfterSelf()
:要获取给定元素之后的同级元素,请使用
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.