gpt4 book ai didi

c# - 显式和隐式 XML namespace

转载 作者:行者123 更新时间:2023-12-04 17:00:53 25 4
gpt4 key购买 nike

我的问题是如何将值设置为具有相同名称但 namespace 不同的两个属性。

使用 C#,在 XML 文档中,我需要为元素分配两个属性。它应该看起来像

文档 xmlns:xmi="uriaddress"
元素 xsi:type="xsitype1"type="type1"


我试过

xElement.SetAttribute("type","uriaddress","xsitype1")

这很好用!

然而,令我惊讶的是,当我尝试设置第二个属性“类型”时,

xElement.SetAttribute("type","type1")

这是有效的,但它也会将属性 xmi:type 重置为与属性“type”相同的值,从而以意想不到的方式更改元素。

现在元素看起来像

元素 xsi:type="type1"type="type1"

有什么办法可以解决这个问题?

最佳答案

这段代码:

    XDocument d = new XDocument();
XNamespace xsi = "uriaddress";
d.Add(
new XElement(
"element",
new XAttribute(XNamespace.Xmlns + "xsi", "uriaddress"),
new XAttribute("type", "foo"),
new XAttribute(xsi + "type", "bar")));
using (XmlWriter xw = XmlWriter.Create(Console.Out))
{
d.WriteTo(xw);
}

d.Element("element").SetAttributeValue("type", "baz");
using (XmlWriter xw = XmlWriter.Create(Console.Out))
{
d.WriteTo(xw);
}

d.Element("element").SetAttributeValue(xsi + "type", "bar");
using (XmlWriter xw = XmlWriter.Create(Console.Out))
{
d.WriteTo(xw);
}

生成此输出(添加空格并删除 XML 声明以提高可读性):
<element xmlns:xsi="uriaddress" type="foo" xsi:type="bar" />

<element xmlns:xsi="uriaddress" type="baz" xsi:type="bar" />

<element xmlns:xsi="uriaddress" type="baz" xsi:type="bat" />

如果您不使用 XDocument (很难从您的原始帖子中看出),此代码产生的结果基本相同:
    XmlDocument d = new XmlDocument();
d.LoadXml("<element xmlns:xsi='uriaddress' type='foo' xsi:type='bar'/>");
Console.WriteLine(d.OuterXml);

d.DocumentElement.SetAttribute("type", "baz");
Console.WriteLine(d.OuterXml);

d.DocumentElement.SetAttribute("type", "uriaddress", "bat");
Console.WriteLine(d.OuterXml);

关于c# - 显式和隐式 XML namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1307679/

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