N
N
notmvp2022-01-20 08:30:33
C++ / C#
notmvp, 2022-01-20 08:30:33

How to generate prefixed XML using XElement (C#)?

Greetings!

A very simple task, but after spending a whole day looking for an answer, I still did not find a solution. Please help.

I need to generate an XML document like this:

<pref:rootItem xmlns:pref="urn://requiredLink">
  <pref:childItem>
    ...
    <pref:mainContent>content</pref:mainContent>
    ...
  </pref:childItem>
</pref:rootItem>

The difficulty lies in the fact that absolutely every element of my document must contain the prefix pref . How to implement this using the XElement class in C#? The mentioned class does not have properties/methods that allow you to directly set the element prefix. Searching for an answer made it clear that this is related to xml namespaces, but I did not find an example of a normal implementation of a similar code.

Initially, I directly tried to set the name with a prefix:
XElement item = new XElement("pref:mainContent", "content");

But this option is invalid and the program throws an Xml.XmlException :
The ':' character, hexadecimal value 0x3A, cannot be included in a name

Suggested type option
XNamespace nameSpace = "urn://requiredLink";
XElement item = new XElement(nameSpace + "mainContent", "content");

and does not come close to giving the desired output. Please help me figure it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
Ukrainskiy, 2022-01-20
@notmvp

This is called namespace. https://docs.microsoft.com/en-us/dotnet/standard/l...

XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XElement(aw + "Child", "child content")
);
Console.WriteLine(root);

<aw:Root xmlns:aw="http://www.adventure-works.com">
  <aw:Child>child content</aw:Child>
</aw:Root>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question