Create or replace node in 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 the wrong XML format).

I need to create or replace (if it already exists) a node in this XML, but I cannot work with XDocumentor XmlDocument, because they need a root element to work, and I cannot add a root element to this XML, because I cannot change more code in the application (Windows Forms application).

What options do I have for this?

Edit 1: Using the @chridam example, I have this method, but it replaces all of the 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");
    }
}
+4
source share
3 answers

Xdocument, , , .

, , node :

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>
*/
+4

XML, DOM, - . node, . DOM. , XML.

+1

http://msdn.microsoft.com/en-us/library/system.xml.xmldocumentfragment%28v=vs.110%29.aspx , .

XmlDocument doc = new XmlDocument();
XmlDocumentFragment frag = doc.CreateDocumentFragment();
frag.InnerXml = @"<Something>....</Something>
<Another>....</Another>
<Other>...</Other>";

Now you can get access to the nodes of a document fragment using ChildNodes, SelectNodes, SelectSingleNodeetc. and manage nodes using DOM methods (e.g., AppendChild) or properties (e.g., InnerText).

0
source

All Articles