C# ASP.net在和XDocument中创建XLink节点
我试图以编程方式向XDocument添加一个新的XLink节点,但.Net似乎将它们创建为原子化的名称空间和名称,我找不到任何代码将XLink节点添加到XML 我的代码如下所示:C# ASP.net在和XDocument中创建XLink节点,c#,asp.net,linq-to-xml,xlink,C#,Asp.net,Linq To Xml,Xlink,我试图以编程方式向XDocument添加一个新的XLink节点,但.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_
//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);
不幸的是,这个新节点如下所示:
<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()的路线,因为这似乎是另一种可能的方式
谢谢
Ryan我会这样做:
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" />
太好了。非常感谢,乔恩。