在没有C#根目录的XML中创建或替换节点 [英] Create or replace node in an XML without root in C#

查看:68
本文介绍了在没有C#根目录的XML中创建或替换节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的XML文件:

I have an XML file like this:

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

此XML文件没有根元素(我知道这是错误的XML格式).

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

我需要创建或替换(如果已经存在)此XML中的一个节点,但是我不能使用 XDocument XmlDocument ,因为它们需要一个根元素起作用,并且我无法在此XML中添加根元素,因为无法在应用程序(Windows窗体应用程序)中更改更多代码.

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?

使用@chridam的示例,我有此方法,但是它替换了整个XML.我需要更改什么?

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

推荐答案

一个人可以使用Xdocument,方法是简单地提供一个可使用的框架,然后在完成后丢弃该框架.

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

这篇关于在没有C#根目录的XML中创建或替换节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆