ASP.net Creating an XLink node in and XDocument

2.3k views Asked by At

I am trying to programmatically add a new XLink node to an XDocument but .Net seems to be creating them as atomized namespaces and names and I can't find any code to add XLink nodes to XML?

My code looks like this:

//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);

Unfortunately this newNode comes out like this:

<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>

But I need the node to look like this in order for it to pass the XML validation:

<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>

Can anybody help? I don't want to go down the String.Replace() route as it seems that this must be possible another way?

Thanks

Ryan

1

There are 1 answers

1
Jon Skeet On BEST ANSWER

I'd do that as:

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"));

This produces XML of:

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