AxD
AxD

Reputation: 3158

XDocument/XElement/XAttribute: How do I create a document with namespaces by creating unattached elements?

I'm creating a DOM tree by creating XElement and XAttribute objects first and then adding them to the XDocument afterwards.

How would I do this if XNamespaces are involved?

Here's some simple MRE code, mimicking mine (It's the CreateTree() method that's important here. The other code is just added for clarification):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace XamlTest
{
  internal class Program
  {
    private static readonly Dictionary<string, string> XamlNamespaces = new Dictionary<string, string>()
    {
      { "xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation" },
      { "xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml" }
    };

    private static readonly Dictionary<string, XNamespace> _ns = XamlNamespaces.Select(ns => new { Key = ns.Key.Length < 6 ? "" : ns.Key[6..], Value = (XNamespace)ns.Value }).ToDictionary(ns => ns.Key, ns => ns.Value);


    internal static void Main()
    {
      CreateDocument();

      Console.ReadKey();
    }

    public static void CreateDocument()
    {
      XElement root = new XElement(_ns[""] + "Section");

      foreach (KeyValuePair<string, XNamespace> ns in _ns)
        root.Add(new XAttribute(ns.Key.Length == 0 ? "xmlns" : XNamespace.Xmlns + ns.Key, ns.Value));

      XDocument xamlDoc = new XDocument(root);
      root.Add(CreateTree());

      Console.WriteLine(xamlDoc.ToString());
    }


    private static List<XElement> CreateTree()
    {
      List<XElement> newElements = [];

      newElements.Add(new XElement(_ns[""] + "Paragraph",
                      new XAttribute(_ns[""] + "FontSize", "12")
                      ));

      return newElements;
    }
  }
}

The result is:

<Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Paragraph p3:FontSize="12" xmlns:p3="http://schemas.microsoft.com/winfx/2006/xaml/presentation" />
</Section>

This is not expected. Excpected would be something like this:

<Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Paragraph FontSize="12"/>
</Section>

Upvotes: 0

Views: 46

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167401

I think you simply want

 newElements.Add(
   new XElement(_ns[""] + "Paragraph",
     new XAttribute("FontSize", "12")
   )
 );

if the FontSize attribute is meant to be in no namespace.

Upvotes: 1

Related Questions