代码之家  ›  专栏  ›  技术社区  ›  Colin Burnett

将XML字符串注入XmlWriter时的XML缩进

  •  18
  • Colin Burnett  · 技术社区  · 17 年前

    XmlTextWriter xtw = new XmlTextWriter("foo.xml", Encoding.UTF8);
    xtw.Formatting = Formatting.Indented;
    xtw.IndentChar = '\t';
    xtw.Indentation = 1;
    
    XmlWriter xw = XmlWriter.Create(xtw);
    

    根据Jeff的MSDN链接更改:

    XmlWriterSettings set = new XmlWriterSettings();
    set.Indent = true;
    set.IndentChars = "\t";
    set.Encoding = Encoding.UTF8;
    
    xw = XmlWriter.Create(f, set);
    

    这不会改变最终结果。


    ...
    string xml = ExternalMethod();
    xw.WriteRaw(xml);
    ...
    

    我的首选方法是使用我已有的设置来执行此操作,并且不必重新加载最终的XML来重新格式化它。我也不希望像XmlReader那样解析XML字符串,然后在我的XmlWriter中模拟它所发现的内容(非常手动的过程)。

    6 回复  |  直到 17 年前
        1
  •  30
  •   aaronb    17 年前

    string xml = ExternalMethod();
    XmlReader reader =  XmlReader.Create(new StringReader(xml));
    xw.WriteNode(reader, true);
    
        2
  •  3
  •   Jeff Yates    17 年前

    你不应该使用 XmlTextWriter ,如MSDN所示,其中说明:

    在.NET Framework 2.0版中 使用创建XmlWriter实例的步骤 Create方法和 XmlWriterSettings类。这允许 你必须充分利用所有的机会 释放有关详细信息,请参阅

    相反,您应该使用 XmlWriter.Create 找你的作家。然后您可以使用 XmlWriterSettings 类来指定缩进之类的内容。

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "\t";
    

    使现代化

        3
  •  2
  •   Colin Burnett    17 年前

    这是到目前为止我得到的最好的。一个非常手动的过程,只支持所写的内容。我的字符串XML只不过是标记、属性和文本数据。如果它支持名称空间、CDATA等,那么它必须相应地增长。

    非常手动,非常混乱,很容易出现错误,但它确实满足了我的偏好。

    private static void PipeXMLIntoWriter(XmlWriter xw, string xml)
    {
        byte[] dat = new System.Text.UTF8Encoding().GetBytes(xml);
        MemoryStream m = new MemoryStream();
        m.Write(dat, 0, dat.Length);
        m.Seek(0, SeekOrigin.Begin);
        XmlReader r = XmlReader.Create(m);
    
        while (r.Read())
        {
            switch (r.NodeType)
            {
                case XmlNodeType.Element:
                    xw.WriteStartElement(r.Name);
    
                    if (r.HasAttributes)
                    {
                        for (int i = 0; i < r.AttributeCount; i++)
                        {
                            r.MoveToAttribute(i);
                            xw.WriteAttributeString(r.Name, r.Value);
                        }
                    }
    
                    if (r.IsEmptyElement)
                    {
                        xw.WriteEndElement();
                    }
                    break;
                case XmlNodeType.EndElement:
                    xw.WriteEndElement();
                    break;
                case XmlNodeType.Text:
                    xw.WriteString(r.Value);
                    break;
    
                default:
                    throw new Exception("Unrecognized node type: " + r.NodeType);
            }
        }
    }
    
        4
  •  2
  •   GreyCloud    15 年前

    private static string FormatXML(string unformattedXml) {
        // first read the xml ignoring whitespace
        XmlReaderSettings readeroptions= new XmlReaderSettings {IgnoreWhitespace = true};
        XmlReader reader = XmlReader.Create(new StringReader(unformattedXml),readeroptions);
    
        // then write it out with indentation
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};                       
        using (XmlWriter writer = XmlWriter.Create(sb, xmlSettingsWithIndentation)) {
            writer.WriteNode(reader, true);
        }
    
        return sb.ToString();
    }
    
        5
  •  1
  •   zam6ak    16 年前

    怎么样:

    string xml = ExternalMethod();
    var xd = XDocument.Parse(xml);
    xd.WriteTo(xw);
    
        6
  •  1
  •   Marijn    14 年前

    我正在寻找这个问题的答案,但是是在VB.net中。

    多亏了科林·伯内特,我解决了这个问题。我做了两个更正:第一,错误 XmlReader settings.IgnoreWhiteSpaces ); 其次,读取器必须在读取属性后返回到元素中。下面您可以看到代码的样子。

    Private Sub PipeXMLIntoWriter(xw As XmlWriter, xml As String)
        Dim dat As Byte() = New System.Text.UTF8Encoding().GetBytes(xml)
        Dim m As New MemoryStream()
        m.Write(dat, 0, dat.Length)
        m.Seek(0, SeekOrigin.Begin)
        Dim settings As New XmlReaderSettings
        settings.IgnoreWhitespace = True
        settings.IgnoreComments = True
        Dim r As XmlReader = XmlReader.Create(m, settings)
    
        While r.Read()
              Select Case r.NodeType
                    Case XmlNodeType.Element
                        xw.WriteStartElement(r.Name)
    
                        If r.HasAttributes Then
                            For i As Integer = 0 To r.AttributeCount - 1
                                r.MoveToAttribute(i)
                                xw.WriteAttributeString(r.Name, r.Value)
                            Next
                            r.MoveToElement()
                        End If
    
                        If r.IsEmptyElement Then
                            xw.WriteEndElement()
                        End If
                        Exit Select
                    Case XmlNodeType.EndElement
                        xw.WriteEndElement()
                        Exit Select
                    Case XmlNodeType.Text
                        xw.WriteString(r.Value)
                        Exit Select
                    Case Else
    
                        Throw New Exception("Unrecognized node type: " + r.NodeType)
                End Select
          End While
    End Sub