gpt4 book ai didi

c# - 使用 C# 将内联 XML 节点转换为 asp.net 中的嵌套节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:55:53 25 4
gpt4 key购买 nike

我有一个如下所示的 XML 文件:

<?xml version="1.0" encoding="utf-8" ?>
<LayoutControl ID="rootlyt" Type="LayoutControl">
<LayoutGroup ID="lgp8" Header="PersonalInfo" IsCollapsed="False" IsLocked="False" Orientation="Vertical" View="GroupBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="380" Height="295" Type="GroupItem" Properties="IsCollapsible=False,IsCollapsed=False,IsLocked=False,">
<Element ID="layout2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="300" Height="25" Label="Name" Background="#00FFFFFF" ContentName="txt2" Type="TextEdit" />
</LayoutGroup>
</LayoutControl>

出于某些原因,我需要从 Element 节点 attributes 创建子节点和嵌套节点。
我想要的输出是:

<?xml version="1.0" encoding="utf-8" ?>
<LayoutControl ID="rootlyt" Type="LayoutControl">
<LayoutGroup ID="lgp8" Header="PersonalInfo" IsCollapsed="False" IsLocked="False" Orientation="Vertical" View="GroupBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="380" Height="295" Type="GroupItem" Properties="IsCollapsible=False,IsCollapsed=False,IsLocked=False,">
<Element >
<ID>layout2</ID>
<HorizontalAlignment>Left</HorizontalAlignment>
<VerticalAlignment>Top</VerticalAlignment>
<Width>300</Width>
<Height>25</Height>
<Label>Name</Label>
<Background>#00FFFFFF</Background>
<ContentName>txt2</ContentName>
<Type>TextEdit</Type>
</Element>
</LayoutGroup>
</LayoutControl>

我该怎么做?
或任何想法、引用、文章...

谢谢。

最佳答案

这是一种可能的方式;对于每个 <Element>的属性添加一个相应的子元素,然后删除所有属性:

var raw = @"<LayoutControl ID='rootlyt' Type='LayoutControl'>
<LayoutGroup ID='lgp8' Header='PersonalInfo' IsCollapsed='False' IsLocked='False' Orientation='Vertical' View='GroupBox' HorizontalAlignment='Left' VerticalAlignment='Top' Width='380' Height='295' Type='GroupItem' Properties='IsCollapsible=False,IsCollapsed=False,IsLocked=False,'>
<Element ID='layout2' HorizontalAlignment='Left' VerticalAlignment='Top' Width='300' Height='25' Label='Name' Background='#00FFFFFF' ContentName='txt2' Type='TextEdit' />
</LayoutGroup>
</LayoutControl>";

var doc = XDocument.Parse(raw);
foreach(var element in doc.Descendants("Element"))
{
//add a series of child elements according to existing attributes
element.Add(
element.Attributes()
.Select(attribute => new XElement(attribute.Name.LocalName, attribute.Value))
);

//remove the attributes
element.Attributes().Remove();
}

Console.WriteLine(doc.ToString());

dotnetfiddle demo

对于更复杂的 XML 转换,请查看 XSLT。

关于c# - 使用 C# 将内联 XML 节点转换为 asp.net 中的嵌套节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com