0

I Need to Code an XML-File in C# using XMLDocument. I extract the desired XML-File and only Need to insert some Elements i Need to add.

The EXPECTED Output should look like this:

<service>
   <coding>
       <system value="https://somethingichanged" />
         <code value="myvalue" />
    </coding>
</service>

However, my Output Looks like this:

<service>
    <coding>
         <system>https://somethingichanged</system>
        <code>myvalue</code>
    </coding>
</service>

Here is my Code:

string[] tag = new string[] { "service", "coding", "system", "code", "http://URI"};
XmlElement Service = m_XMLDoc.CreateElement(tag[0], tag[4]);
XmlElement Coding = m_XMLDoc.CreateElement(tag[1], tag[4]);
Service.AppendChild(Coding);

//Fill Element
XmlNode System = m_XMLDoc.CreateNode(XmlNodeType.Element, tag[2], tag[4]);
XmlNode Code = m_XMLDoc.CreateNode(XmlNodeType.Element, tag[3], tag[4]);
System.InnerText = "https://somethingichanged";
Coding.AppendChild(System);

Code.InnerText = myTSS[i].ToString();
Coding.AppendChild(Code);

How does the correct Code look like? Thanks!

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
V.Kirsch
  • 13
  • 5

2 Answers2

0

You should created attribuites, not xml elements.

So use:

System.Attributes.Append( m_XMLDoc.CreateAttribute("value", "https://somethingichanged"));

Code.Attributes.Append( m_XMLDoc.CreateAttribute("value", myTSS[i].ToString()));

instead of

System.InnerText = "https://somethingichanged";
Code.InnerText = myTSS[i].ToString();
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
0

.Net LINQ to XML makes it much easier to achieve in one single statement of code.

c#

void Main()
{
    string[] tag = new string[] { "service", "coding", "system", "code", "http://URI"};

    XElement xml = new XElement(tag[0],
                        new XElement(tag[1],
                            new XElement(tag[2], new XAttribute("value", tag[4])),
                            new XElement(tag[3], new XAttribute("value", "myvalue")))
                        );
}

Output XML:

<service>
  <coding>
    <system value="http://URI" />
    <code value="myvalue" />
  </coding>
</service>
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21