public class OperXml
{
XmlDocument xmlDoc = new XmlDocument();
public void CreateNode(XmlDocument xmlDoc,XmlNode parentNode,string name,string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
//添加节点
parentNode.AppendChild(node);
}
/// <summary>
/// 创建XML
/// </summary>
/// <param name="RootName">根节点名字</param>
/// <param name="NodeName">子节点名字</param>
/// <param name="path">路径</param>
/// <param name="Elements">元素名字</param>
/// <param name="Names">元素名字集合</param>
public void NewXml(string RootName, string NodeName, string path,string[] Elements, string[] Names)
{
//创建类型声明节点
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//创建根节点
XmlElement root = xmlDoc.CreateElement(RootName);
xmlDoc.AppendChild(root);
XmlElement person = xmlDoc.CreateElement(NodeName); //添加独立子节点
for (int i = 0; i < Elements.Length;i++ )
{
CreateNode(xmlDoc, person, Elements[i], Names[i]);
}
root.AppendChild(person);
try
{
xmlDoc.Save(path);
}
catch (Exception f)
{
//显示错误信息
MessageBox.Show(f.Message);
}
}
/// <summary>
/// XML转DataTable
/// </summary>
/// <param name="strXMLPath">路径</param>
public DataTable XMLToDataTable(string strXMLPath)
{
StringReader stream = null;
XmlTextReader reader = null;
StreamReader sr = null;
try
{
if (strXMLPath.Length <= 0)
{
return new DataTable();
}
sr = new StreamReader(strXMLPath);
string strXmlContent = sr.ReadToEnd();
stream = new StringReader(strXmlContent);
reader = new XmlTextReader(stream);
DataSet ds = new DataSet();
ds.ReadXml(reader);
return ds.Tables[0];
}
catch (System.Exception vErr)
{
MessageBox.Show(vErr.Message);
}
finally
{
if (sr != null)
sr.Close();
if (reader != null)
reader.Close();
}
return new DataTable();
}
/// <summary>
/// DataTable转XML
/// </summary>
/// <param name="strXMLPath">路径</param>
public bool DataTableToXML(DataTable dtTable, string strXMLPath)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
StreamWriter sw = null;
try
{
stream = new MemoryStream();
writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
dtTable.WriteXml(writer, XmlWriteMode.IgnoreSchema);
int nCount = (int)stream.Length;
byte[] arr = new byte[nCount];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, nCount);
UTF8Encoding utf = new UTF8Encoding();
string strContent = utf.GetString(arr).Trim();
sw = new StreamWriter(strXMLPath);
sw.Write(strContent);
return true;
}
catch (System.Exception vErr)
{
MessageBox.Show(vErr.Message);
return false;
}
finally
{
if (writer != null)
{
writer.Close();
}
if (sw != null)
{
sw.Close();
}
}
}
}
XML创建、转DataTable
最新推荐文章于 2019-09-02 11:05:00 发布