0

I have Special XML file with utf-16 encoding type. this file used to store data and I need to Edit it Using C# windows forms Application

<?xml version="1.0" encoding="utf-16"?>
<cProgram    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="b0eb0c7e-f4de-4bc7-9e62-7a086a8c2fn8" Version="16.01" xmlns="cProgram">
  <Serie>N    </Serie>
  <No>123456</No>
  <type>101</type>
  <Dataset4>larg data here 2 million char</Dataset4>
</cProgram>123456FF896631N    4873821012013-06-14

the problem is: it is not ordinary XML file Because at the very End of the file I have a string line too, and that would give this error

Data at the root level is invalid. Line x, position x

when I try to load it as xml file

I tried to temporary replace the last line and get it back after I change the inner text, and it works But I lost the declaration Line and I didn't find a way to rewrite it when I have that text at the end of the file !_
so I need to change the InnerText of (Serie) and (No) nodes but I don't Want to lose the declaration Line or the string text at the end of the file

4

3 回答 3

0

请允许我在使用 doc.Load(filepath); 时回答我的问题;它总是给出令人不安的最后一行和 C# 使用 UTF-8 作为默认值来处理 xml 文件的错误原因。但在这个问题中它是 UTF-16 所以我找到了一个非常短的方法来做到这一点并用字符串替换内部文本想

 string text = File.ReadAllText(filepath);
        text = text.Replace("<Serie>N", "<Serie>"+textBox1.Text);
        text = text.Replace("<Nom>487382","<Nom>"+textBox2.Text);
       //saving file with UTF-16
        File.WriteAllText("new.xml", text , Encoding.Unicode);

与此 [博客] 相关的问题:如何将此字符串保存到 XML 文件中?“与问题相关的答案比与问题相关的要多得多”

于 2014-04-26T05:14:34.433 回答
0

XDocument.Save()如果声明最初存在,则应保留 XML 声明行。我还检查了您的 XML 并按预期保存了声明行:

var xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<cProgram    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" ID=""b0eb0c7e-f4de-4bc7-9e62-7a086a8c2fn8"" Version=""16.01"" xmlns=""cProgram"">
  <Serie>N    </Serie>
  <No>123456</No>
  <type>101</type>
  <Dataset4>larg data here 2 million char</Dataset4>
</cProgram>";
var doc = XDocument.Parse(xml);
doc.Save("test.xml");

因此,您可以实现您的想法以临时替换最后一行并在更改内部文本后将其取回。

仅供参考,XDocument.ToString()方法不写 XML 声明行,但.Save()方法。与此相关的问题:如何使用 XDocument 打印 <?xml version="1.0"?>

于 2014-04-25T06:56:41.740 回答
0

试试这段代码:

string line = "";
string[] stringsperate = new string[] { "</cProgram>" };
using (StreamReader sr = new StreamReader("C://blah.xml"))
{
     line = sr.ReadToEnd();
     Console.WriteLine(line);
}
string text = line.Split(stringsperate, StringSplitOptions.None)[0];
text += "</cProgram>";
XmlDocument xd = new XmlDocument();
xd.LoadXml(text);
Console.Read();

希望这可以帮助

于 2014-04-25T05:18:23.150 回答