c# - 使用 xslt 和 c# 从中选择一个 xml 节点并根据其值添加更多节点
问题描述
作为 xslt 的初学者,我在编写 xslt 时遇到问题。场景如下:从属性名称为“值”的属性中,我应该检查它是否包含“^”符号。如果它包含,我应该为每个由“^”分割的值添加更多属性标签。我尝试在 xslt 中这样做,但对我得到的输出感到疯狂。//逻辑
试过这个,但无法弄清楚需要在 xsl foreach 中添加什么逻辑才能添加新的属性标签。
请包括我可以学习的任何 xslt 资源。
我可以做 c# xml 的东西吗
Function()
{
var splitstring[]=string.Split('^');
XmlAttribute.SetAttribute('Val1','splitstring[0]');
XmlAttribute.SetValue('Val2',splitstring[1]);
}
输入 xml:
<Observation>
<Property Name="Type" Value="1234"/>
<Property Name="Code" Value="CodeA"/>
<Property Name="Value1" Value="12345^Val1^6789"/>
<Property Name="Unit" Value=""/>
<Property Name="Status" Value=""/>
</Observation>
这是输入xml
输出 xml:
<Observation>
<Property Name="Type" Value="1234"/>
<Property Name="Code" Value="CodeA"/>
<Property Name="Value1" Value="12345"/>
<Property Name="Value2" Value="Val1"/>
<Property Name="Value3" Value="6789"/>
<Property Name="Unit" Value=""/>
<Property Name="Status" Value=""/>
</Observation>
How can i integrate a c# code (because it's easy) or an xslt logic to make this happen?
解决方案
尝试 Xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication137
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> properties = doc.Descendants("Property").ToList();
for (int i = properties.Count - 1; i >= 0; i-- )
{
XElement property = properties[i];
string value = (string)property.Attribute("Value");
if (value.Contains("^"))
{
property.ReplaceWith(ReplaceElement(property));
}
}
}
static List<XElement> ReplaceElement(XElement element)
{
List<XElement> elements = new List<XElement>();
string name = (string)element.Attribute("Name");
string baseName = Regex.Match(name, @"[^\d]+").Value;
string value = (string)element.Attribute("Value");
string[] splitValues = value.Split(new char[] { '^' }).ToArray();
for (int i = 1; i <= splitValues.Length; i++)
{
elements.Add(new XElement("Property", new XAttribute[] {
new XAttribute("Name", baseName + i.ToString()),
new XAttribute("Value", splitValues[i - 1])
}));
}
return elements;
}
}
}
推荐阅读
- python - 如何返回任意两个字母之间的最大距离(az 忽略大小写)?
- linux - 同时使用iperf和ping mininet
- sql-server - 执行动态 SQL 并插入到存储过程中创建的表中?
- elasticsearch - 获取弹性搜索的相关数据
- reactjs - React 表单优化
- javascript - HTML, Javascript 游戏,我想找到一种在页面显示上播放声音的方法
- spring-boot - 将 Jersey 与 Spring Boot 一起使用
- xamarin.forms - 无法在 AppBar 上更改颜色
- python - 在 Python > 3 上使用带有部分和映射失败的多处理脚本,在 2.7 上工作正常,无法腌制“_thread.lock”
- jestjs - Mobx react 测试组件