创建的xml文件为什么是空的
时间: 2023-10-22 19:11:43 浏览: 163
在C#中创建和读取XML文件的实现方法
可能是因为你没有向xml文件中写入任何内容。在创建xml文件后,你需要使用相应的编程语言或工具将信息写入xml文件中,才能在文件中看到内容。以下是一些写入xml文件的示例代码:
使用Python语言写入xml文件:
```python
import xml.etree.ElementTree as ET
root = ET.Element("root")
doc = ET.SubElement(root, "doc")
ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"
tree = ET.ElementTree(root)
tree.write("filename.xml")
```
使用Java语言写入xml文件:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class WriteXMLFile {
public static void main(String[] args) throws IOException, XMLStreamException {
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(new FileWriter(new File("filename.xml")));
xmlStreamWriter.writeStartDocument();
xmlStreamWriter.writeStartElement("root");
xmlStreamWriter.writeStartElement("doc");
xmlStreamWriter.writeStartElement("field1");
xmlStreamWriter.writeAttribute("name", "blah");
xmlStreamWriter.writeCharacters("some value1");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("field2");
xmlStreamWriter.writeAttribute("name", "asdfasd");
xmlStreamWriter.writeCharacters("some value2");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.flush();
xmlStreamWriter.close();
}
}
```
使用C#语言写入xml文件:
```csharp
using System;
using System.Xml;
public class WriteXML {
public static void Main() {
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("filename.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteStartElement("doc");
writer.WriteStartElement("field1");
writer.WriteAttributeString("name", "blah");
writer.WriteString("some value1");
writer.WriteEndElement();
writer.WriteStartElement("field2");
writer.WriteAttributeString("name", "asdfasd");
writer.WriteString("some value2");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
```
这些是只是一些示例代码,你可以根据自己的需要进行修改。
阅读全文