下面的代碼工作有具有四個空格壓痕(請仔細看一看的輸入文檔)輸入文檔。這只是一個例子:當然你可以通過製表符縮進實現對輸入文檔的支持。
private static void ConvertToXml(Stream inputStream, Stream outputStream)
{
const int oneIndentLength = 4; // One level indentation - four spaces.
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true
};
using (var streamReader = new StreamReader(inputStream))
using (var xmlWriter = XmlWriter.Create(outputStream, xmlWriterSettings))
{
int previousIndent = -1; // There is no previous indent.
string line;
while ((line = streamReader.ReadLine()) != null)
{
var indent = line.TakeWhile(ch => ch == ' ').Count();
indent /= oneIndentLength;
var elementName = line.Trim();
if (indent <= previousIndent)
{
// The indent is the same or is less than previous one - write end for previous element.
xmlWriter.WriteEndElement();
var indentDelta = previousIndent - indent;
for (int i = 0; i < indentDelta; i++)
{
// Return: leave the node.
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteStartElement(elementName);
// Save the indent of the previous line.
previousIndent = indent;
}
}
}
客戶端代碼:
using (var inputStream = File.OpenRead(@"Input file path"))
using (var outputStream = File.Create(@"Output file path"))
{
ConvertToXml(inputStream, outputStream);
}
輸入文檔:
sampleroot
rootHeader
miscInformation
Creation
DocumentIdentification
Identifier
Message_Type
Notes
StandardDocumentationIdentification
Standard
Version
Receiver
Name
lok
Location
Sender
Name
lok2
msgref
DocumentIdentifier
HoldInformation
Name
Date
ReleaseInformation
Date
HoldDocumentReference
AlternativeIdentifier
Authority
Identifier
Notes
ReleaseDocumentReference
AlternativeIdentifier
Authority
Identifier
Notes
輸出文件:
<?xml version="1.0" encoding="utf-8"?>
<sampleroot>
<rootHeader>
<miscInformation>
<Creation />
<DocumentIdentification>
<Identifier />
<Message_Type />
<Notes />
</DocumentIdentification>
<StandardDocumentationIdentification>
<Standard />
<Version />
</StandardDocumentationIdentification>
</miscInformation>
<Receiver>
<Name />
<lok />
<Location />
</Receiver>
<Sender>
<Name />
<lok2 />
</Sender>
<msgref>
<DocumentIdentifier />
<HoldInformation>
<Name />
<Date />
</HoldInformation>
<ReleaseInformation>
<Date />
</ReleaseInformation>
</msgref>
<HoldDocumentReference>
<AlternativeIdentifier>
<Authority />
<Identifier />
</AlternativeIdentifier>
<Notes />
</HoldDocumentReference>
<ReleaseDocumentReference>
<AlternativeIdentifier>
<Authority />
<Identifier />
</AlternativeIdentifier>
<Notes />
</ReleaseDocumentReference>
</rootHeader>
</sampleroot>
請發表你的代碼,或者是更具描述性的[你有什麼試過嗎?(http://mattgemmell.com/2008/12/08/what-have-yo U型試過/)。 – Brian
您能否爲示例添加預期的輸出XML文檔? –
@ user1354345,我添加了另一個答案。 –