0

XML の属性を更新しようとしています。私の問題は、更新して後でxmlを読むと、例外が発生することです。私は問題を探していましたが、方法はわかりませんが、xml の最後に、一般的な終了タグの最後の文字が表示されます。場合によっては、3 文字または 2 文字が最後に続くか、1 文字だけ続くこともあり>ます。この問題は常に発生するとは限りません。二回目にあるときもあれば、四回目にあるときもあれば、十回目にあるときもある... 以下にスニペットを入れます。どうもありがとう、そして私の英語でごめんなさい。

PD: Linq は使っていません

私のXML

// At the end of xml file appears this fragment
<?xml version="1.0"?>
<MYPRINCIPALTAG>
    <TAG DATE="01/01/01"></TAG>
</MYPRINCIPALTAG>AG>

より多くのコード;-)

// Read XML
System.IO.FileStream fs = new System.IO.FileStream (path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
XmlTextReader reader = new XmlTextReader (fs);
while (reader.Read ()) {
switch (reader.NodeType) {
   case XmlNodeType.Element:
      switch (reader.Name) {
        case 'TAG':
            string pubdate = reader.GetAttribute (0);
            break;
        }
        break;
    }
fs.Close(); 

public static XmlNode OpenXmlNode(string path, ref System.IO.FileStream fs, ref XmlDocument doc) {
     fs = new System.IO.FileStream (path, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
     doc = new XmlDocument ();
     doc.Load (fs);
     fs.Flush ();
     fs.Close ();
     return doc.DocumentElement;
}

public static void CloseXmlNode(string path, ref System.IO.FileStream fs, ref XmlDocument doc) {
    fs = new System.IO.FileStream (path, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
    doc.Save (fs);
    fs.Flush ();
    fs.Close ();
}

 public static Boolean UpdateXML(string path, string id_tag) {
     try {
        System.IO.FileStream fs = null;
        XmlDocument doc = new XmlDocument ();
        XmlNode element = OpenXmlNode (path, ref fs, ref doc);
        // Change Date
        element.ChildNodes[0].Attributes.GetNamedItem ("date").Value = DateTime.Now.ToString ("dd/MM/yy");
        for (int count = 1; count < doc.DocumentElement.ChildNodes.Count; count++) {
           if ((doc.DocumentElement.ChildNodes[count].Attributes.GetNamedItem ("ID").Value).Equals (id_tag)) {
              for (int i = 0; i < doc.DocumentElement.ChildNodes[count].ChildNodes[0].ChildNodes.Count; i++) {
                doc.DocumentElement.ChildNodes[count].ChildNodes[0].ChildNodes[i].Attributes.GetNamedItem ("STATE").Value = "ok";
              }
              break;
           }
        }
        CloseXmlNode (path, ref fs, ref doc);
        return true;
     } catch (Exception e) {
        return false;
     }
}
4

1 に答える 1

1

fs.flush(); を実行してみてください。fs.Close(); の前に このような

doc.Save(fs);
fs.Flush();
fs.Close();

さらに良い。コードを(静的関数を使用して)記述した方法では、ファイルストリーム(IMO)を使用することから恩恵を受けていないようです。関数 OpenXmlNode() および CloseXmlNode() を次のように変更します。

public static XmlNode OpenXmlNode(string path, ref XmlDocument doc) 
{
     doc = new XmlDocument (); 
     doc.Load (path); 
     return doc.DocumentElement; 
} 
public static void CloseXmlNode(string path, ref XmlDocument doc) 
{ 
    doc.Save (path); 
}
于 2012-12-11T17:07:28.440 に答える