首页 > 解决方案 > 使用 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?

标签: c#xmlxslt

解决方案


尝试 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;
        }

    }

}

推荐阅读