gpt4 book ai didi

c# - ASP.net 在 XDocument 中创建 XLink 节点

转载 作者:行者123 更新时间:2023-12-02 01:20:40 24 4
gpt4 key购买 nike

我正在尝试以编程方式将新的 XLink 节点添加到 XDocument,但 .Net 似乎将它们创建为原子化命名空间和名称,并且我找不到任何代码来将 XLink 节点添加到 XML?

我的代码如下所示:

//read in the current XML content
XDocument content = XDocument.Parse(xmlContent);

//add a new node called large images
XElement newNode = new XElement("large_images", "");
newNode.SetAttributeValue("{xmlns}xlink", "http://www.w3.org/1999/xlink");
newNode.SetAttributeValue("{xlink}type", "simple");
newNode.SetAttributeValue("{xlink}href", "tcm:5-550");
newNode.SetAttributeValue("{xlink}title", "of1_454x340.jpg");
content.Add(newNode);

不幸的是,这个 newNode 的结果是这样的:

<large_images p1:xlink="http://www.w3.org/1999/xlink" p2:type="simple" p2:href="tcm:5-550" p2:title="of1_454x340.jpg" xmlns:p2="xlink" xmlns:p1="xmlns"></large_images>

但是我需要节点看起来像这样才能通过 XML 验证:

<large_images xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="tcm:5-550" xlink:title="of1_454x340.jpg"></large_images>

有人可以帮忙吗?我不想走 String.Replace() 路线,因为这似乎必须有另一种方式?

谢谢

瑞恩

最佳答案

我会这样做:

XNamespace ns = "http://www.w3.org/1999/xlink";

XElement newNode = new XElement("large_images",
new XAttribute(XNamespace.Xmlns + "xlink", ns),
new XAttribute(ns + "type", "simple),
new XAttribute(ns + "href", "tcm:5-550"),
new XAttribute(ns + "title", "of1_454x340.jpg"));

这会生成以下 XML:

<large_images xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
xlink:href="tcm:5-550" xlink:title="of1_454x340.jpg" />

关于c# - ASP.net 在 XDocument 中创建 XLink 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977882/

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