Create this XML in C # with XmlWriter

2

How can I do this:

<Amt>
    <cbc:price>340.00</cbc:price>
</Amt>

This is my code so far:

const string cur = "Ccy=" + @"""EUR";
                writer.WriteStartElement("Amt");
                writer.WriteElementString("InstdAmt", cur, "340.00");
                writer.WriteEndElement();

And this is my code result so far:

<Amt>
  <InstdAmt xmlns="Ccy=&quot;EUR">340.00</InstdAmt>
</Amt>
    
asked by Gian Paul Ramírez Pacheco 15.08.2017 в 18:07
source

2 answers

2
  

The syntax of the XML that you want to obtain is incorrect, because   you are trying to create the prefix cbc without its corresponding namespace.

To generate your XML document you have to do:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (var ms = new MemoryStream())
{           
    // default: utf-8
    using (XmlWriter writer = XmlWriter.Create(ms, settings)) 
    {               
        writer.WriteStartElement("Amt");

        writer.WriteAttributeString("xmlns", "cbc", null, "urn:ejemplo");

        writer.WriteStartElement("cbc", "price", "urn:ejemplo");
        writer.WriteString("340.00");
        writer.WriteEndElement();       
    }

    Console.WriteLine(new UTF8Encoding().GetString(ms.ToArray()));
}

DEMO

You'll get:

<?xml version="1.0" encoding="utf-8"?>
<Amt xmlns:cbc="urn:ejemplo">
  <cbc:price>340.00</cbc:price>
</Amt>

Reference:

answered by 15.08.2017 / 20:01
source
-2

It's simple, although I believe it through XmlDocument

You always have to place a root node, in my case it will be root

XmlDocument dataUser = new XmlDocument();
dataUser.LoadXml("<root></root>");

to create an element, just use the createElement, followed by the name of your node in parentheses and with quotes.

XmlElement statusElement = dataUser.CreateElement("status");

in this way you will have created a node.

To add a value to this node, you just have to do it using an InnerText followed by the value

statusElement.InnerText = "1";

Even though it seems to be over, you still do not save the node, to save it you should only use AppendChild followed by parentheses and the name of your node

dataUser.DocumentElement.AppendChild(statusElement);

When you finish all your nodes and only after you have finished, all the blank spaces disappear

dataUser.PreserveWhitespace = true;

This so that you do not have mistakes later. and finally save your XML file

dataUser.Save("../../Data/user.xml");

Pd: you must leave two folders to get to the root of your project

Luck

    
answered by 15.08.2017 в 18:48