4

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");
    }
}
2
  • How ..... looks like? Is it multi-line xml data or each element is represented as single line in file? Commented Feb 18, 2014 at 14:36
  • The ..... are single line but the new element (or maybe is already there and it should be replaced) is a multi-line. Commented Feb 18, 2014 at 14:38

3 Answers 3

7

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>
*/
Sign up to request clarification or add additional context in comments.

2 Comments

Seems pretty good to me. One thing to note - there exists xDoc.Root which you can use instead of xDoc.Element("Root")
@SergeyBerezovskiy yours is an excellent point. I will update it to reflect that.
1

You can use http://msdn.microsoft.com/en-us/library/system.xml.xmldocumentfragment%28v=vs.110%29.aspx to work with such a fragment e.g.

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

Now you can access nodes in the document fragment with ChildNodes, SelectNodes, SelectSingleNode and so on and manipulate nodes with the DOM methods (like AppendChild) or properties (like InnerText).

2 Comments

I keep having the problem that the XML is in a file and not in a string... how do i open that file and get the string to perform the code you have?
Use msdn.microsoft.com/en-us/library/ms143368%28v=vs.110%29.aspx e.g. string fragXml = File.ReadAllText("fragment.xml"); then frag.InnerXml = fragXml;.
1

If you are unable to manipulate XML using DOM your option is text manipulation tools. Try regular expressions to locate the node you need and then remove the text using string manipulation routines. However adding root element to the source text is an easy way to have the DOM working. You can remove it later , after processing the XML.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.