打开xml:
string xmlstring = ""; private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.InitialDirectory = Application.StartupPath; dialog.Filter = "All Files|*.*|xml file(*.xml)|*.xml"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { string filepath = dialog.FileName.ToString(); string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); textBox1.Text = filepath; using (StreamReader sr = new StreamReader(filepath, Encoding.Default))//如果乱码,可改为System.Text.Encoding.UTF-8;或者System.Text.Encoding.GBK { string str; string line = ""; while ((str = sr.ReadLine()) != null) { line += str; } xmlstring = line; } } richTextBox1.Text = xmlstring; }
格式化xml:
private string FormatXml(string sUnformattedXml) { StringReader Reader = new StringReader(sUnformattedXml); XmlDocument xd = new XmlDocument(); xd.Load(Reader); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); XmlTextWriter xtw = null; try { xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.Indentation = 1; xtw.IndentChar = '\t'; xd.WriteTo(xtw); } finally { if (xtw != null) xtw.Close(); } return sb.ToString(); }
3.获取xml内容:
public string AllChildNode(string xml) { StringReader Reader = new StringReader(xml); XmlDocument doc = new XmlDocument(); doc.Load(Reader); string str = ""; XmlNode root = doc.FirstChild; if (root.HasChildNodes) { for (int i = 0; i < root.ChildNodes.Count; i++) { str += root.ChildNodes[i].InnerText; } } return str; }