public static void Main()
{
string ids="1,2,3,4,5,6,9";
string filePath = "c://c/d/qq.xml";
string xmlPath = "getsomething/news/list/store";
string subString = xmlPath.Substring(0,xmlPath.LastIndexOf('/'));
string now = xmlPath.Substring(xmlPath.LastIndexOf('/')+1);
if (!IsExists(filePath))
{
Exists(filePath);
}
doc.Load(filePath);
xml = (XmlElement)doc.FirstChild;
string parentPath = xmlPath.Substring(0, xmlPath.LastIndexOf('/'));
string nowNode = xmlPath.Substring(xmlPath.LastIndexOf('/') + 1);
XmlNode node = doc.SelectSingleNode(parentPath);
XmlNode oldNode = doc.SelectSingleNode(xmlPath);
if (node == null)
{
node = CreateXmlNode(parentPath);
XmlElement el = doc.CreateElement(nowNode);
XmlAttribute attr = doc.CreateAttribute("ids");
attr.Value = ids;
el.Attributes.Append(attr);
node.AppendChild(el);
}
else
{
XmlElement el = doc.CreateElement(nowNode);
XmlAttribute attr = doc.CreateAttribute("ids");
attr.Value = ids;
el.Attributes.Append(attr);
if (oldNode == null)
{
node.AppendChild(el);
}
else
{
node.ReplaceChild(el, oldNode);
}
}
doc.Save(filePath);
Console.ReadKey();
}
public static XmlNode CreateXmlNode(string xmlPath)
{
string[] xmls = xmlPath.Split('/');
string root = "";
XmlNode parent =xml;
for (int i = 0; i < xmls.Length;i++)
{
XmlNode node = doc.DocumentElement.SelectSingleNode(root+"/"+xmls[i]);
if (node == null)
{
XmlElement xmle = doc.CreateElement(xmls[i]);
parent.AppendChild(xmle);
}
root = root + "/" + xmls[i];
parent =doc.DocumentElement.SelectSingleNode(root);
}
return parent;
}