本文介绍了如何在c#中创建子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 嗨i希望在c#中为其中一个项目创建子节点,但是我的代码会生成这个 < C > < 主题 > Spaceman < / Subject > < 项目 > 程序员 < 子 > IT < / Child > < Child > 硬件程序员< / Child > < / Items > < 项目 > Mo < 儿童 > IT < / Child > < 儿童 > 硬件程序员< / Child > < / Items > < 项目 > 程序员 < 子 > IT < / Child > < 子 > 硬件程序员< /儿童 > < / Items > < / C > d这是我的代码 XmlTextWriter writer = new XmlTextWriter( test.xml,Encoding.UTF8); writer.WriteStartDocument(); writer.WriteStartElement( C); writer.WriteStartElement( Subject); writer.WriteString(txtSubject.Text); writer.WriteEndElement(); // 主题 foreach ( string item in listBox1.Items) { writer.WriteStartElement( Items); writer.WriteString(item); foreach ( string items in listBox2.Items) { writer.WriteStartElement( Child) ; writer.WriteString(items); writer.WriteEndElement(); // Child } writer.WriteEndElement(); // Items } writer.WriteEndElement( ); // C writer.WriteEndDocument(); writer.Close(); 有人可以告诉我的代码在哪里做错了它会让xml像这样 With Respect 解决方案 试试这个: foreach ( string item in listBox1.Items) { writer。 WriteStartElement(item); // writer.WriteString(item); foreach ( string items in listBox2.Items) { writer.WriteStartElement( Child); writer.WriteString(items); writer.WriteEndElement(); // Child } writer.WriteEndElement(); // item } Hii want to make child node for one of these items in c# but my code make this<C><Subject>Spaceman</Subject><Items>Programmer<Child>IT</Child><Child>Hardware Programmer</Child></Items><Items>Mo<Child>IT</Child><Child>Hardware Programmer</Child></Items><Items>Programmer<Child>IT</Child><Child>Hardware Programmer</Child></Items></C>and this is my codeXmlTextWriter writer = new XmlTextWriter("test.xml", Encoding.UTF8);writer.WriteStartDocument();writer.WriteStartElement("C");writer.WriteStartElement("Subject");writer.WriteString(txtSubject.Text);writer.WriteEndElement();//Subjectforeach (string item in listBox1.Items){ writer.WriteStartElement("Items"); writer.WriteString(item); foreach (string items in listBox2.Items) { writer.WriteStartElement("Child"); writer.WriteString(items); writer.WriteEndElement();//Child } writer.WriteEndElement();//Items}writer.WriteEndElement();//Cwriter.WriteEndDocument();writer.Close();can someone tell where of my code doing wrong to it make xml like thisWith Respect 解决方案 Try this:foreach (string item in listBox1.Items){ writer.WriteStartElement(item ); //writer.WriteString(item); foreach (string items in listBox2.Items) { writer.WriteStartElement("Child"); writer.WriteString(items); writer.WriteEndElement(); //Child } writer.WriteEndElement(); //item} 这篇关于如何在c#中创建子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-06 01:52