Customizing XML Namespaces Using the System.Xml.Linq API

I am having trouble creating XML on the following lines:

<Root xmlns:brk="http://somewhere">
<child1>
    <brk:node1>123456</brk:node1>
    <brk:node2>500000000</brk:node2>
</child1>
</Root>

This code will give me most of the way, but I cannot get the namespace "brk" in front of the nodes;

 var rootNode = new XElement("Root");
 rootNode.Add(new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere"));

 var childNode = new XElement("child1");
 childNode.Add(new XElement("node1",123456));
 rootNode.Add(childNode);

I tried this:

XNamespace brk = "http://somewhere";
childNode.Add(new XElement(brk+"node1",123456));

and this one

XNamespace brk = "http://somewhere";
childNode.Add(new XElement("brk:node1",123456));

but both are exceptions.

+3
source share
3 answers

You are almost there, but you made one simple mistake in your first code example. I believe this is what you need:

XNamespace brk = "http://somewhere.com";
XElement root = new XElement("Root",
    new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));

XElement childNode = new XElement("child1");
childNode.Add(new XElement(brk + "node1",123456));
root.Add(childNode);

The main difference here is that I add node1in childNodeas follows:

childNode.Add(new XElement(brk + "node1",123456));

This code given XmlWriterand XDocumentgives me the result:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:brk="http://somewhere.com">
  <child1>
    <brk:node1>123456</brk:node1>
  </child1>
</Root>

For more information, XNamespacesee MSDN ..

+3

, , :

XElement root = new XElement("Root",
    new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));

:

XElement root = new XElement(brk + "Root",
    new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));
0

.

 using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using System.Xml.Serialization;

    namespace CreateSampleXML
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();            
                XNamespace xm = "http://somewhere.com";
                XElement rt= new XElement("Root", new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));
                XElement cNode = new XElement("child1");
                cNode.Add(new XElement(xm + "node1", 123456));
                cNode.Add(new XElement(xm + "node2", 500000000));
                rt.Add(cNode);
                XDocument doc2 = new XDocument(rt);
                doc2.Save(@"C:\sample3.xml");
            }
        }       
    }
0

Source: https://habr.com/ru/post/1702925/


All Articles