c# - 将缩进文本转换为 XML

标签 c# xml schema

我有一个基于文本的文件,其中缩进表示 XML 文件的每个 XML 标记。

如何在 C# 中将此文本转换为示例 XML?
我有点迷路了。我必须计算空格并在列表中回顾以确定标签何时应该关闭。

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       

最佳答案

以下代码适用于具有四个空格缩进 的输入文档(请仔细查看输入文档)。这只是一个示例:您当然可以实现对带有制表符缩进的输入文档的支持。

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>

关于c# - 将缩进文本转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14736646/

相关文章:

c# - 枚举 ConcurrentDictionary 时是否可能遗漏初始项?

java - 格式化 XML 的十进制值

python - 当我在 Odoo 中上传图像时,如何在对话框窗口中按图像格式进行过滤?

jasper-reports - iReport - 参数化架构名称?

database - Scala slick 检查 DDL 表和数据库模式表是否具有相同的形状

javascript - 如何在 JavaScript/JQuery 中输入时验证或屏蔽一些特殊字符

c# - MVC 3 WebGrid.Table 页脚参数

c# - 如何使用代码在 Unity 中切换复选框?

xml - JSTL - 解析不适​​用于具有命名空间的元素

javascript - 使用 Collection2 在 Meteor 中插入空白的嵌入式架构