问题描述
我想将XML文件的内容读取到任何网页或文本文件中,这些XML文件是使用我自己创建的解析器从EDI解析它们的结果,但是,标记是无效的,因为我自己创建了它们,所以制作新标签的常规做法还是应该使用现有标签?如果是,如何读取新标签?
干杯,
Hi,
I would like to read the content of an XML file into whatever webpage or textfile, these XML files are the result of parsing them from EDI using a parser I made myself, however, the tags are not valid since I made them myself, so is it conventional to make new tags or should i be using existing tags? if yes, how can I read my new tags?
cheers,
推荐答案
string XmlAttributeToText(int depth, string attributeName, string value) {
//...
return //... whatever you want
} //XmlAttributeToText
string XmlNodeToText(int depth, System.Xml.XmlNodeType nodeType, string name, string value) {
//...
return //... whatever you want
} //XmlNodeToText
string textFileName = //...
string xmlFileName = //...
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(textFileName, false, System.Text.Encoding.UTF8)) {
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlFileName)) {
while (reader.Read()) {
string nodeContent = XmlNodeToText(reader.Depth, reader.NodeType, reader.Name, reader.Value);
writer.WriteLine(nodeContent); //or writer.Write, whatever is required
if (reader.HasAttributes) {
reader.MoveToNextAttribute();
string attributeContent = XmlAttributeToText(reader.Depth, reader.Name, reader.Value);
writer.WriteLine(attributeContent); //or writer.Write, whatever is required
} //if
} //loop
} //using XmlReader // reader is disposed here
} //using StreamWriter // writer is disposed here, file buffer is flashed and file is closed, which is even more important
您还可以使用XML阅读器选项来忽略注释,处理指令;您可以忽略对上述循环不感兴趣的节点类型;换句话说,以适合您目标的方式来编程从XML映射到文本的映射规则.
Also you can use XML reader options to ignore comment, processing instructions; you can ignore node types you are not interested in the loop shown above; in other words — program the mapping rules for mapping from XML to text the ways suitable for your goal.
这篇关于XML转换为普通文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!