XDocument/xelement/xattribute: Wie erstelle ich ein Dokument mit Namespaces, indem ich nicht gebundene Elemente erstelle
Posted: 27 Jan 2025, 09:25
Ich erstelle einen DOM -Baum, indem ich Xelement und xatTribute zuerst erstellen und dann dem xDocument danach hinzufügen.
Wie wie Würde ich das tun, wenn XnameSpace s beteiligt wäre? Code wird nur zur Klarstellung hinzugefügt): < /p>
Das Ergebnis ist:
Wie wie Würde ich das tun, wenn XnameSpace s beteiligt wäre? Code wird nur zur Klarstellung hinzugefügt): < /p>
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace XamlTest
{
internal class Program
{
private static readonly Dictionary XamlNamespaces = new Dictionary()
{
{ "xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation" },
{ "xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml" }
};
private static readonly Dictionary _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 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 CreateTree()
{
List newElements = [];
newElements.Add(new XElement(_ns[""] + "Paragraph",
new XAttribute(_ns[""] + "FontSize", "12")
));
return newElements;
}
}
}
Code: Select all
< /code>
Dies wird nicht erwartet. Excwork wäre so etwas wie folgt: < /p>