c# - How do I remove the parent node without removing its child nodes as well?
问题描述
I have the following XML structure:
<root>
<list>
<item1>item 1</item1>
<item2>item 2</item2>
<item3>item 3</item3>
<item4>item 4</item4>
<generated-items>
<item5>item 5</item5>
<item6>item 6</item6>
</generated-items>
</list>
<list>
<item1>item 1</item1>
<item2>item 2</item2>
<item3>item 3</item3>
<item4>item 4</item4>
<generated-items>
<item5>item 5</item5>
<item6>item 6</item6>
</generated-items>
</list>
<list>
<item1>item 1</item1>
<item2>item 2</item2>
<item3>item 3</item3>
<item4>item 4</item4>
<generated-items>
<item5>item 5</item5>
<item6>item 6</item6>
</generated-items>
</list>
</root>
What I want to do is remove the parent tag of the repeating part of the XML file, which should result in the following outcome:
<root>
<list>
<item1>item 1</item1>
<item2>item 2</item2>
<item3>item 3</item3>
<item4>item 4</item4>
<item5>item 5</item5>
<item6>item 6</item6>
</list>
<list>
<item1>item 1</item1>
<item2>item 2</item2>
<item3>item 3</item3>
<item4>item 4</item4>
<item5>item 5</item5>
<item6>item 6</item6>
</list>
<list>
<item1>item 1</item1>
<item2>item 2</item2>
<item3>item 3</item3>
<item4>item 4</item4>
<item5>item 5</item5>
<item6>item 6</item6>
</list>
</root>
What is the best way to do this? I tried to copy the child nodes and paste them inside the repeating list element to make them part of that section, then removing the generating-items element all together.. Although I'm not sure if this is the most optimal way of doing this, and it gets messy real fast this way.
解决方案
The best way is to use XSLT-1.0 to transform your input XML to your desired output XML.
This can be achieved by using XslCompiledTransform
.
The following stylesheet (transform.xslt
) does the job:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Identity template -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="generated-items">
<xsl:copy-of select="*" />
</xsl:template>
</xsl:stylesheet>
The necessary C# code is identical to the example in the link:
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("transform.xslt");
// Execute the transform and output the results to a file.
xslt.Transform("input.xml", "output.xml");
Then output.xml
contains the data you want.
推荐阅读
- c++ - CMake Linker 无法使用静态函数构建可执行文件
- arrays - 确定数组/字符串中最大匹配序列的有效方法(在 Ruby 中)?
- r - 如何计算R中两个时间戳列的平均值?
- xslt - XSL:按元素匹配是否与按元素名称匹配?
- validation - gSheet - Google Apps 脚本 - 复制 DataValidation - 下拉菜单:“正在加载...”
- bootstrap-4 - Bootstrap Radio Group 无法在选项卡面板中选择
- amazon-web-services - AWS boto3 在创建 AMI 后无法放置标签
- openmdao - 安装 OpenMDAO 2.6.0 错误
- terraform - 地形 | aws_route53_record | 构建变更集时出错:InvalidChangeBatch
- winapi - 带有 RIDEV_NOHOTKEYS 的原始输入键盘显示经典的 Alt+Tab 菜单