gpt4 book ai didi

c# - 如何在 C# 中添加具有不同前缀/命名空间的 xml 属性?

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

我需要能够创建如下所示的 XML 文档:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rootprefix:rootname
noPrefix="attribute with no prefix"
firstprefix:attrOne="first atrribute"
secondprefix:attrTwo="second atrribute with different prefix">

...other elements...

</rootprefix:rootname>

这是我的代码:

XmlDocument doc = new XmlDocument();

XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
doc.AppendChild(declaration);

XmlElement root = doc.CreateElement("rootprefix:rootname", nameSpaceURL);
root.SetAttribute("schemaVersion", "1.0");

root.SetAttribute("firstprefix:attrOne", "first attribute");
root.SetAttribute("secondprefix:attrTwo", "second attribute with different prefix");

doc.AppendChild(root);

不幸的是,我得到的带有第二个前缀的第二个属性根本没有前缀。它只是“attrTwo”——就像 schemaVersion 属性。

那么,有没有办法在 C# 中为根元素中的属性设置不同的前缀?

最佳答案

这只是给您的指南。也许你可以这样做:

        NameTable nt = new NameTable();
nt.Add("key");

XmlNamespaceManager ns = new XmlNamespaceManager(nt);
ns.AddNamespace("firstprefix", "fp");
ns.AddNamespace("secondprefix", "sp");

root.SetAttribute("attrOne", ns.LookupPrefix("fp"), "first attribute");

root.SetAttribute("attrTwo", ns.LookupPrefix("sp"), "second attribute with different prefix");

这将导致:

        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rootprefix:rootname schemaVersion="1.0" d1p1:attrOne="first attribute" d1p2:attrTwo="second attribute with different prefix" xmlns:d1p2="secondprefix" xmlns:d1p1="firstprefix" xmlns:rootprefix="ns" />

希望对您有所帮助!

关于c# - 如何在 C# 中添加具有不同前缀/命名空间的 xml 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17428699/

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