简体   繁体   English

C#中如何用“:”(冒号)合并父元素和子元素

[英]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&#x0027;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();

Demo fiddle here .演示小提琴在这里

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

相关问题 如何在C#中获取xml父元素中的所有子元素 - How to get all child elements in the parent element of xml in c# 如何在xml元素中添加冒号? Linq到xml C# - How to add a colon inside xml element? Linq to xml C# 如何使用 C# 从 XML 获取所有子元素名称及其父元素名称? - How to get all the child element name along with their parent element name from XML using C#? 硒:如何在同一父元素下选择另一个子元素(C#) - Selenium: How to choose another child element under the same parent element (C#) 列表<parent>持有子元素而不丢失属性 C#</parent> - List<Parent> holding Child element without losing properties C# 子元素与父元素匹配时的C#XmlSerializer xmlns - C# XmlSerializer xmlns in child element matching parent C#,LINQ获取指定父元素的子元素 - C#, LINQ Getting Child elements of a Specified Parent Element 使用C#XmlSerializer将父元素名称继承到子元素中 - Inherit parent element name into child with C# XmlSerializer 如何使用 C# 从多级嵌入式 MongoDB 文档中获取具有相应父级的确切子元素 - How to get the exact child element with corresponding parent only from multilevel embedded MongoDB document using C# XML C# 如果多个子元素中的任何一个包含数组中的值,如何删除父元素 - XML C# How to remove parent element if any of multiple child elements contains a value in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM