修改现有XML中的XmlElement

时间:2013-06-05 11:25:51

标签: c# xml winforms

我在运行时使用以下代码编写xml

if (fileDialog.FileName != "" && resultSaveDialog == System.Windows.Forms.DialogResult.OK)
            {
                fileDialog.OpenFile();
                XDocument Xdoc = new XDocument(new XElement("LinkAnalysis"));
                if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "LA_img\\LAIMG.xml"))
                    Xdoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "LA_img\\LAIMG.xml");
                else
                {
                    Xdoc = new XDocument();
                    XElement xmlstart = new XElement("LinkAnalysis");
                    Xdoc.Add(xmlstart);
                }
                XElement xml = new XElement("ImgInfo",
                  new XElement("Number", selectedvertex.Name),
                  new XElement("ImgPath", AppDomain.CurrentDomain.BaseDirectory + "LA_img\\" + fileDialog.SafeFileName));                    
                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "VerbaLinks.xml"))
                {
                    DataSet dsXML = new DataSet();
                    bool chkName = false;
                    dsXML.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "LA_img\\LAIMG.xml");
                    try
                    {
                        // Here i am checking if number is already exist in xml
                        chkName = dsXML.Tables["ImgInfo"].AsEnumerable().Any(s => s.Field<string>("Number").ToLower() == selectedvertex.Name);
                       // If exist, I wanna update that element with new ImgPath.
                    }
                    catch
                    {
                        chkName = false;
                    }
                }

                if (Xdoc.Descendants().Count() > 0)
                    Xdoc.Descendants().First().Add(xml);
                else
                {
                    Xdoc.Add(xml);
                }
                Xdoc.Element("LinkAnalysis").Save(AppDomain.CurrentDomain.BaseDirectory + "LA_img\\LAIMG.xml");

在xml中添加新元素之前,我正在检查天气它已经存在于xml中,如果是,我只想更新corrsponding Number的ImgPath属性

这里是示例xml

<?xml version="1.0" encoding="utf-8"?>
<LinkAnalysis>
<ImgInfo>
  <Number>xyz</Number>
  <ImgPath>D:\Projects\VERBALinks\VERBALinks\bin\Debug\LA_img\grid.png</ImgPath>
</ImgInfo>
<ImgInfo>
  <Number>pqr</Number>
  <ImgPath>D:\Projects\VERBALinks\VERBALinks\bin\Debug\LA_img\1367408385_Social network.png</ImgPath>
</ImgInfo>
<ImgInfo>
  <Number>wxy</Number>
  <ImgPath>D:\Projects\VERBALinks\VERBALinks\bin\Debug\LA_img\Link_Analysis.png</ImgPath>
</ImgInfo>  
</LinkAnalysis>

0 个答案:

没有答案