简体   繁体   中英

How to merge Parent Element and Child element with " : " (colon) in C#

Input Xml:

<title>Discourse interaction between <italic>The New York Times</italic> and <italic>China Daily</italic></title> <subtitle>The case of Google&#x0027;s departure</subtitle>

Required 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 . You can see this by formatting your containing element xml with indentation:

<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() :

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

Demo fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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