简体   繁体   English

通过代码添加xml标记

[英]Adding xml tag via code

I'm writing an application in C#. 我正在用C#编写一个应用程序。 I already an .xml file that is not empty and I want to add new values to it, without deleting the existing values. 我已经是一个非空的.xml文件,我想为它添加新值,而不删除现有值。

I have tried this code: 我试过这段代码:

First: 第一:

FileStream docNewUser = new FileStream(@"C:\\MyApp\\MySubDir\\Data\\" + pr + ".xml", FileMode.Open);
XmlTextWriter xmlNewUser = new XmlTextWriter(docNewUser, null);
xmlNewUser.WriteStartDocument();

xmlNewUser.WriteStartElement("RootEl");//root 

xmlNewUser.WriteStartElement("Zapis");

xmlNewUser.WriteStartElement("Name");
xmlNewUser.WriteString(txtEnterName.Text);
xmlNewUser.WriteEndElement();

xmlNewUser.WriteEndElement();//end of zapis                

this.Close();

Second: 第二:

FileStream docNewUser = new FileStream(@"C:\\MyApp\\MySubDir\\Data\\" + pr + ".xml", FileMode.Open);
XmlTextWriter xmlNewUser = new XmlTextWriter(docNewUser, null);
xmlNewUser.WriteStartDocument();

xmlNewUser.WriteStartElement("RootEl");//root-ot

xmlNewUser.WriteStartElement("Zapis");

xmlNewUser.WriteStartElement("Name");
xmlNewUser.WriteString(txtEnterName.Text);
xmlNewUser.WriteEndElement();

xmlNewUser.WriteEndElement();//end of zapis                

xmlNewUser.WriteElementString("Ime", null, txtEnterName.Text);

this.Close();

Third: 第三:

FileStream docNewUser = new FileStream(@"C:\\MyApp\\MySubDir\\Data\\" + pr + ".xml", FileMode.Open);
XmlTextWriter xmlNewUser = new XmlTextWriter(docNewUser, null);
xmlNewUser.WriteStartDocument();

xmlNewUser.WriteStartElement("Zapis");

xmlNewUser.WriteStartElement("Name");
xmlNewUser.WriteString(txtEnterName.Text);
xmlNewUser.WriteEndElement();

xmlNewUser.WriteEndElement();//end of zapis                

xmlNewUser.WriteElementString("Ime", null, txtEnterName.Text);

this.Close();

I think the problem is that the stream doesn't know where to put the new value. 我认为问题是流不知道将新值放在何处。 some more information: the root element is already entered. 更多信息:已输入根元素。

If your .NET version supports it, use LINQ to XML . 如果您的.NET版本支持它,请使用LINQ to XML (Caveat: I'm not an expert, and there's probably a more elegant way to write this.) (警告:我不是专家,而且可能有更优雅的方式来写这个。)

// Without error handling
var root = XElement.Load(@"C:\Users\TrueWill\Downloads\Foo.xml");

var product =
    (from item in root.Elements("item")
    where item.Element("name").Value == "Product1"
    select item)
    .Single();

product.Add(new XElement("size", "small"));

root.Save(@"C:\Users\TrueWill\Downloads\FooCopy.xml");

My test file (before): 我的测试文件(之前):

<?xml version="1.0" encoding="utf-8"?>
<test>
<item><name>Product1</name></item>
<item><name>Product2</name></item>
</test>

My test file copy (after) (I copied rather than replacing): 我的测试文件副本(之后)(我复制而不是替换):

<?xml version="1.0" encoding="utf-8"?>
<test>
  <item>
    <name>Product1</name>
    <size>small</size>
  </item>
  <item>
    <name>Product2</name>
  </item>
</test>

When you write XML to a file this way, it always overwrites what was in the file before. 当您以这种方式将XML写入文件时,它总是会覆盖之前文件中的内容。 If you want to write to it using XmlTextWriter , you would have to copy the current content first, and write the new elements at the proper position. 如果要使用XmlTextWriter写入它,则必须先复制当前内容,然后将新元素写入正确的位置。 Don't forget that you can't read from and write to the same file at the same time, so you have to use a temporary file and overwrite the original with it. 不要忘记您无法同时读取和写入同一文件,因此您必须使用临时文件并用它覆盖原始文件。 Or you read the whole file into a string first. 或者您首先将整个文件读入字符串。 Or write your result into a string first. 或者先将结果写入字符串。

But a better solution might be to use XDocument (or XmlDocument ) to load the whole document, modify it and then save it. 但更好的解决方案可能是使用XDocument (或XmlDocument )加载整个文档,修改它然后保存它。 (Doing this is not a good idea if the XML file is huge.) (如果XML文件很大,这样做不是一个好主意。)

Use XmlDocument: 使用XmlDocument:

XmlDocument doc = new XmlDocument();
doc.Load("filepath");
XmlNode node = doc["MainNode"]["subnode1"]["subnode2"]; //to fetch the node after which you'd like to add something.
XmlElement stuffToAdd = doc.CreateNode("nodename");
stuffToAdd.InnerText = "the value of your added node";
node.AddChild(stuffToAdd);
doc.Save("filepath");

I'm doing this out of memory, so the names of the methods are aproximate. 我这样做是因为内存不足,所以这些方法的名称都是近似的。

As said in another answer, loading big XML files using XmlElement can be costy, because it is fully loaded in memory when you call Load() . 正如在另一个答案中所说的,使用XmlElement加载大型XML文件可能很容易,因为当您调用Load()时它会在内存中完全加载。

Is there a reason you are using XmlTextWriter? 你有没有理由使用XmlTextWriter? I find the LINQ to XML alternatives much easier. 我发现LINQ to XML替代方案更容易。

your code would be something like below; 你的代码就像下面那样;

XElement el = new XElement("Zapis");
el.Add(new XElement("Name",txtEnterName.Text))
el.Save(@"C:\\MyApp\\MySubDir\\Data\\" + pr + ".xml")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM