如何将List <string>转换为xml

时间:2017-04-25 04:30:49

标签: c# xml linq linq-to-xml

我需要将String的List转换为XML格式,我使用下面的代码将List转换为XML

XElement xmlElements = new XElement("DocumentElement", _UserIDs.Select(i => new XElement("BadgeNo", i)));

当前结果:

<DocumentElement>
 <BadgeNo>IMS001</BadgeNo>
 <BadgeNo>IMS002</BadgeNo>
 <BadgeNo>IMS003</BadgeNo>
 <BadgeNo>IMS022</BadgeNo>
 <BadgeNo>WAN35166</BadgeNo>
</DocumentElement>

但是我需要更多东西,我需要像这样添加一个额外的节点。如何实现以下输出

预期结果:

<DocumentElement>
 <GroupInput>
   <BadgeNo>IMS001</BadgeNo>
 </GroupInput>
 <GroupInput>
   <BadgeNo>IMS002</BadgeNo>
 </GroupInput>
 <GroupInput>
   <BadgeNo>IMS003</BadgeNo>
 </GroupInput>
 <GroupInput>
    <BadgeNo>IMS022</BadgeNo>
 </GroupInput>
 <GroupInput>
   <BadgeNo>WAN35166</BadgeNo>
 </GroupInput>
</DocumentElement>

先谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

在传递新的“BadgeNo”元素作为参数时选择新的“GroupInput”元素:

XElement xmlElements = new XElement("DocumentElement", 
                            _UserIDs.Select(i => 
                                        new XElement("GroupInput", 
                                                new XElement("BadgeNo", i))
                            )
                       );