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

大兔子大兔子 提交于 2021-02-20 18:55:46

问题


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");
    }
}

回答1:


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



回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/21856420/create-or-replace-node-in-an-xml-without-root-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!