XML 数据格式如下:
<?xml version="1.0" encoding="utf-8"?>
<PeopleInfo>
<PeopleInfoList str_Epc="350000000000000000000000" str_name="chpdirect">
<str_PeopleID>peopleid0000</str_PeopleID>
<str_PeopleName>peoplename0000</str_PeopleName>
<str_PeopleUnit>11111111111</str_PeopleUnit>
</PeopleInfoList>
</PeopleInfo>
一:创建主架构的 XML 文件
XmlWriterSettings settring = new XmlWriterSettings ();
settring .Indent = true ;
settring .NewLineOnAttributes = true ;
XmlWriter writer = XmlWriter .Create (CommonUseXMLPrevFilePath , settring );
writer .WriteStartDocument ();
writer .WriteStartElement ("PeopleInfo" );
writer .WriteEndElement ();
writer .WriteEndDocument ();
writer .Flush ();
writer .Close ();
二:添加数据
if (!File .Exists (CommonUseXMLPrevFilePath ))
{
CreateXMLFile ();
}
this .document .Load (CommonUseXMLPrevFilePath );
XmlElement vehNode = this .document .CreateElement ("PeopleInfoList" );
vehNode .SetAttribute ("str_Epc" , epc );
vehNode .SetAttribute ("str_name" , "chp" );
XmlElement prev_livestock_ID = this .document .CreateElement ("str_PeopleID" );
prev_livestock_ID .InnerText = id ;
XmlElement prev_time = this .document .CreateElement ("str_PeopleName" );
prev_time .InnerText = name ;
XmlElement prev_address = this .document .CreateElement ("str_PeopleUnit" );
prev_address .InnerText = unit ;
vehNode .AppendChild (prev_livestock_ID );
vehNode .AppendChild (prev_time );
vehNode .AppendChild (prev_address );
//this.document.GetElementsByTagName("PeopleInfo")[0].AppendChild(vehNode);
this .document .SelectSingleNode ("PeopleInfo" ).AppendChild (vehNode );
this .document .Save (CommonUseXMLPrevFilePath );
三:修改数据
if (!File .Exists (CommonUseXMLPrevFilePath ))
{
CreateXMLFile ();
}
this .document .Load (CommonUseXMLPrevFilePath );
XmlNodeList nodeList = this .document .SelectSingleNode ("PeopleInfo" ).ChildNodes ;
foreach (XmlNode xn in nodeList )
{
XmlElement xe = (XmlElement )xn ;
XmlNodeList nls = xe .ChildNodes ;
foreach (XmlNode xn1 in nls )
{
XmlElement xe2 = (XmlElement )xn1 ;
if (xe2 .Name == "str_PeopleUnit" )
{
xe2 .InnerText = "11111111111" ;
}
}
//if (xe.GetAttribute("str_name") == "chp")
//{
//xe.SetAttribute("str_name", "chpdirect");
//XmlNodeList nls = xe.ChildNodes;
//foreach (XmlNode xn1 in nls)
//{
// XmlElement xe2 = (XmlElement)xn1;
// if (xe2.Name == "str_PeopleUnit")
// {
// xe2.InnerText = "00000000";
// }
//}
//}
}
this .document .Save (CommonUseXMLPrevFilePath );// 保存。
四:删除
if (!File .Exists (CommonUseXMLPrevFilePath ))
{
CreateXMLFile ();
}
this .document .Load (CommonUseXMLPrevFilePath );
XmlNodeList nodeList = this .document .SelectSingleNode ("PeopleInfo" ).ChildNodes ;
foreach (XmlNode xn in nodeList )
{
XmlElement xe = (XmlElement )xn ;
if (xe .GetAttribute ("str_Epc" ) == "350000000000000000000100" )
{
xe .RemoveAttribute ("str_Epc" );
}
else if (xe .GetAttribute ("str_Epc" ) == "350000000000000000000101" )
{
//xe.RemoveAllAttributes();
xe .RemoveAll ();
}
}
this .document .Save (CommonUseXMLPrevFilePath );// 保存。