gpt4 book ai didi

c# - 如何在xml元素内添加冒号? Linq to xml C#

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:23 25 4
gpt4 key购买 nike

我正在从 linq 查询生成一个 XML 文件。生成了 xml 元素,但是我想在每个元素中添加一个前缀,因此结果如下:-

XDocument xDoc =null;

xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("EmpLists",
new XElement("Employee",
new XElement("EmpId", '1'),
new XElement("Name", "Sam"),
new XElement("Sex", "Male"))));

我应该怎么做才能让元素打印出前缀“CP:”,如下所示?

<?xml version="1.0" encoding="utf-8" ?>
<CP:EmpLists>
<CP:Employee>
<CP:EmpId>1</CP:EmpId>
<CP:Name>Sam</CP:Name>
<CP:Sex>Male</CP:Sex>
<CP:Address>
<CP:Street>7A Cox Street</CP:Street>
<CP:City>Acampo</CP:City>
<CP:State>CA</CP:State>
<CP:Zip>95220</CP:Zip>
</CP:Address>
</CP:Employee>
<CP:Employee>
<CP:EmpId>2</CP:EmpId>
<CP:Name>Lucy</CP:Name>
<CP:Sex>Female</CP:Sex>
<CP:Address>
<CP:Street>Jess Bay</CP:Street>
<CP:City>Alta</CP:City>
<CP:State>CA</CP:State>
<CP:Zip>95701</CP:Zip>
</CP:Address>
</CP:Employee>
</CP:EmpLists>

最佳答案

这对我有用:

var url = "YOUR_NS_URL";
var ns = XNamespace.Get(url);

var xDoc =
new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement(ns + "EmpLists",
new XAttribute(XNamespace.Xmlns + "CP", url),
new XElement(ns + "Employee",
new XElement(ns + "EmpId", '1'),
new XElement(ns + "Name", "Sam"),
new XElement(ns + "Sex", "Male"))));

我得到这个 XML:

<CP:EmpLists xmlns:CP="YOUR_NS_URL">
<CP:Employee>
<CP:EmpId>1</CP:EmpId>
<CP:Name>Sam</CP:Name>
<CP:Sex>Male</CP:Sex>
</CP:Employee>
</CP:EmpLists>

关于c# - 如何在xml元素内添加冒号? Linq to xml C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245731/

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