2010-12-07 71 views
0

我在这里要做的是看看该元素是否存在于xml文档中,如果存在,那么我想修改它的内部文本。如果它不存在,我想创建它并为它创建适当的内部文本。然而,当一个元素确实存在时,我试图将其内部文本更改为比整个xml文件写入更短的东西。XML.Save文件写神秘

我的代码:

<?xml version="1.0" encoding="utf-8"?> 
<MyXMLFile> 
    <Source>C:\Users\Dacto\Desktop\</Source> 
    <Destination>C:\Program Files\Adobe</Destination> 
</MyXMLFile> 

较短的内部文本后:

<?xml version="1.0" encoding="utf-8"?> 
<MyXMLFile> 
    <Source>C:\Users\Dacto\Desktop\Napster</Source> 
    <Destination>C:\Users</Destination> 
</MyXMLFile>/MyXMLFile> 

见 “额外”/ MyXMLFile用较短的内部文本修改之前

   XmlDocument xmldoc = new XmlDocument(); 
       xmldoc.Load(path); 
       XmlNodeList felement = xmldoc.GetElementsByTagName(Element); 
       FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); 
       if (felement.Count == 0) 
       { 
        XmlElement elmRoot = xmldoc.DocumentElement; 
        XmlElement xmlele = xmldoc.CreateElement(Element); 
        xmlele.AppendChild(xmldoc.CreateTextNode(data)); 
        elmRoot.AppendChild(xmlele); 
        xmldoc.Save(fs); 
       } 
       else 
       { 
        felement[0].InnerText = data; 
        xmldoc.Save(fs); 
       } 
       fs.Close(); 

XML文件>发生了什么事?

回答

2

由于输出不是有效的XML,因此XmlDocument.Save不太可能生成文件的全部内容。鉴于此,我怀疑当创建FileStream时,您应该提供一个不同的参数,而不是FileMode.Open - FileMode.Create将确保文件在写入之前被截断 - 当前它被覆盖,将旧内容留在原位如果新文件不足以覆盖它。

+0

这就是似乎正在发生的事情,我将其更改为FileMode.Truncate - 它工作:) – Dacto 2010-12-07 08:04:18

0

问题在于他们用你写出文件的方式,而不是用xml。如果你尝试类似,

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); 
byte[] info = new UTF8Encoding(true).GetBytes("AAAAA"); 
fs.Write(info, 0, info.Length);   

你应该看到:

AAAAA version="1.0" encoding="utf-8"?> 
<MyXMLFile> 
    <Source>C:\Users\Dacto\Desktop\</Source> 
    <Destination>C:\Program Files\Adobe</Destination> 
</MyXMLFile> 

相反FileMode.Open的,你想FileMode.Create,因此,如果它存在的文件被你写它之前截断已经。

0

另一个必须保存XmlDocument的选项是通过使用XmlWriter而不是FileStream。

XmlDocument xmldoc = new XmlDocument(); 
    xmldoc.Load(path); 
    XmlNodeList felement = xmldoc.GetElementsByTagName(Element); 

    XmlWriterSettings settings = new XmlWriterSettings(); 
    settings.Indent = true; 

    using (XmlWriter wr = XmlWriter.Create(path), settings)) 
    { 
     if (felement.Count == 0) 
     { 
      XmlElement elmRoot = xmldoc.DocumentElement; 
      XmlElement xmlele = xmldoc.CreateElement(Element); 
      xmlele.AppendChild(xmldoc.CreateTextNode(data)); 
      elmRoot.AppendChild(xmlele); 
      xmldoc.Save(wr); 
     } 
     else 
     { 
      felement[0].InnerText = data; 
      xmldoc.Save(wr); 
     } 
    } 

另外,如果你继续使用你原来的FileStream方法,那么我会建议在using语句包裹它就像我与的XmlWriter上面做,如果你这样做,那么你就可以摆脱的FS。 Close()语句。