XmlDocument将节点组合到同一行中

时间:2015-01-05 15:28:32

标签: c# xml

我有一个编辑XML文件的应用程序。

问题是,在保存文件后,一些节点合并到一行。

示例: 我想编辑子节点B

<root>
    <A>
      <B>
        <C>somedata</C>
        ...
      </B>
    </A>
</root>

编辑后我得到:

<root>
    <A>
     <B><C>EditedData</C></B>
    </A>
</root>

我的代码是

public static bool WriteNodeInnerText(List<string> NodesHirarchi, string InnerText, string PathToXml)
{
    if (NodesHirarchi.Count == 0) return false;

    XmlDocument doc = new XmlDocument();
    doc.Load(PathToXml);

    doc.PreserveWhitespace = true;

    XmlNode xmlNode;
    StringBuilder nodesPath = new StringBuilder();
    NodesHirarchi.ForEach(x => nodesPath.Append(string.Format("//{0}", x)));
    try
    {
        xmlNode = doc.SelectSingleNode(nodesPath.ToString());
    }
    catch (System.Xml.XPath.XPathException ex)
    {
        Console.WriteLine(ex.Data);
        return false;
    }

    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true,
        IndentChars = "  ",
        NewLineChars = "\r\n",
        NewLineHandling = NewLineHandling.Replace,
    };

    using (XmlWriter writer = XmlWriter.Create(PathToXml,settings))
    {
        xmlNode.InnerText = InnerText;
        doc.Save(writer);
    }
    return true;
}

请帮助我解决它+任何关于代码的评论将不胜感激

0 个答案:

没有答案