Search code examples
c#xmllinq-to-xmlxmldocument

Create or replace node in an XML without root in C#


I have an XML file like this:

<Something>....</Something>
<Another>....</Another>
<Other>...</Other>

This XML file does not have a root element (I know that this is a wrong XML format).

I need to create or replace (if it already exists) a node in this XML, but I can't work with XDocument or XmlDocument because they need a root element to work, and I can't add a root element to this XML because I can't change more code in the Application (Windows forms application).

What are my options to perform this?

Edit 1: Using @chridam's sample, I have this method, but it replaces the entire XML. What do I need to change?

public void ReEscribirNodoXML(string pathXml, string nodoName, string nodeContent)
{
    if (File.Exists(pathXml))
    {
        XmlValidatingReader vr = new XmlValidatingReader(pathXml, XmlNodeType.Element, null);
        while (vr.Read())
        {
            Debug.WriteLine("NodeType: {0} NodeName: {1}", vr.NodeType, vr.Name);
        }

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

        var writer = XmlWriter.Create(pathXml, settings);
        writer.WriteStartElement(nodoName);
        writer.WriteRaw(nodeContent);
        writer.WriteEndElement();

        writer.Flush();
    }
    else
    {
        throw new Exception("I#Error");
    }
}

Solution

  • One can use Xdocument by simply supplying a framework to work with, then discarding that framework when done.

    Here is the fragment going in, a change made, a new node added and a fragment going out:

    var fragment = @"<Something>abc</Something>
    <Another>def</Another>
    <Other>ghi</Other>";
    
    var xDoc = XDocument.Parse("<TempRoot>" + fragment + "</TempRoot>");
    
    xDoc.Descendants("Another").First().Value = "Jabberwocky";
    xDoc.Root.Add(new XElement("Omega", "Man"));
    
    var fragOut = 
       string.Join(Environment.NewLine, xDoc.Root
                                            .Elements()
                                            .Select (ele => ele.ToString()));
    
    Console.WriteLine (fragOut);
    /* Prints out
    <Something>abc</Something>
    <Another>Jabberwocky</Another>
    <Other>ghi</Other>
    <Omega>Man</Omega>
    */