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

标签 c# asp.net linq-to-xml xlink

我正在尝试以编程方式将新的 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/

相关文章:

C# 在这种情况下使用 "this"关键字?

c# - 从 asp.net 上的另一个文件夹引用 dotnetnuke.dll

c# - 从xml中的属性获取值

c# - 如何使用 XmlSerializer 对 xHtml 文本进行 sanitizer ?

asp.net - 请求超时。 Web 服务器未能在指定时间内响应

c# - 使用 MemoryStream 的 xml 末尾有很多意外的 "nul"字符

c# - 错误 :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

c# - 我如何跟踪 DRY-ly 状态?

c# - OrderedDictionary 和正则表达式

asp.net - Elmah 应用程序名称配置