VB.NET XMLWriter:如何更改标题中的内容?

时间:2009-06-22 15:55:19

标签: vb.net xmlwriter

我需要制作一个XML文件 - 而且合作伙伴对标题很贴切。显然,标题必须是这样的:

<?xml version="1.0"?>

但每当我创建一个XML文件时,我都会得到类似这样的无关属性:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

我的黑客想要停止使用XMLWriter来制作文件,以便我可以更好地控制标题; “没问题,我只是编写一个循环,将自己的XML标记作为StreamWriter或其他东西,忘记这个XMLWriter对象......”但我必须承认,到目前为止,XMLWriter的使用相当优雅;肯定有一些东西,我可以改变XMLWriterSettings对象,说“请停止将自定义属性放入XML标题”,对吗?

这是相关的VB代码:

    Dim settings As New XmlWriterSettings()
    settings.Indent = True
    settings.IndentChars = "    "
    settings.NewLineChars = "\n"
    Using writer As XmlWriter = XmlWriter.Create(strFileName, settings)
            writer.WriteStartDocument(True)
            For Each kvp As KeyValuePair(Of String, String) In dictArguments

                 Dim key As String = kvp.Key
                 Dim value As String = kvp.Value

                 writer.WriteStartElement(key)
                 writer.WriteString(value)
                 writer.WriteEndElement()

            Next

    End Using

完美地运作;但我找不到控制标题的方法。我当然可以找到一种完全删除它的方法,但这不是我们想要做的。

编辑:感谢您的帮助;到目前为止,一旦我们删除了WriteStartDocument,它现在不再显示standalone = yes。但我不能让它停止添加编码。有什么想法吗?

5 个答案:

答案 0 :(得分:10)

这样做的一种方法是使用WriteProcessingInstruction方法自己控制初始处理指令:

    Dim settings As New XmlWriterSettings()
    settings.Indent = True
    settings.IndentChars = "    "
    Using writer As XmlWriter = XmlWriter.Create(strFileName, settings)
        writer.WriteProcessingInstruction("xml", "version='1.0'")
        writer.WriteStartElement("root")
        For Each kvp As KeyValuePair(Of String, String) In dictArguments

            Dim key As String = kvp.Key
            Dim value As String = kvp.Value

            writer.WriteStartElement(key)
            writer.WriteString(value)
            writer.WriteEndElement()

        Next
        writer.WriteEndElement()

    End Using

请注意,我还添加了一个“root”元素,以防你的字典包含多个元素(我猜测没有字典键值是“root”):)

答案 1 :(得分:2)

我知道问题问题已经过了几个月,但是我觉得有必要提一下(长期存在的)解决方案,我偶然发现了这个问题。它确实消除了整个xmldeclaration,你需要做的就是通过写一个proccesing指令重新编写你需要的声明。

XmlFragmentWriter - Omiting the Xml Declaration and the XSD and XSI namespaces

这是VB中的类

Imports System.Xml
Imports System.IO
Imports System.Text

Class XmlFragmentWriter
Inherits XmlTextWriter

Public Sub New(ByVal w As TextWriter)
    MyBase.New(w)
End Sub

Public Sub New(ByVal w As Stream, ByVal encoding As Encoding)
    MyBase.New(w, encoding)
End Sub

Public Sub New(ByVal filename As String, ByVal encoding As Encoding)
    MyBase.New(New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
End Sub


Private _skip As Boolean = False

Public Overrides Sub WriteStartAttribute(ByVal prefix As String, ByVal localName As String, ByVal ns As String)
    ' STEP 1 - Omits XSD and XSI declarations. 
    ' From Kzu - http://weblogs.asp.net/cazzu/archive/2004/01/23/62141.aspx
    If prefix = "xmlns" AndAlso (localName = "xsd" OrElse localName = "xsi") Then
        _skip = True
        Return
    End If
    MyBase.WriteStartAttribute(prefix, localName, ns)

End Sub

Public Overrides Sub WriteString(ByVal text As String)
    If _skip Then
        Return
    End If
    MyBase.WriteString(text)

End Sub

Public Overrides Sub WriteEndAttribute()
    If _skip Then
        ' Reset the flag, so we keep writing.
        _skip = False
        Return
    End If
    MyBase.WriteEndAttribute()

End Sub

Public Overrides Sub WriteStartDocument()
    ' STEP 2: Do nothing so we omit the xml declaration.
End Sub
End Class

以及此处的用法:

    Dim f As New XmlSerializer(GetType(OFXg))
      Dim w As New XmlFragmentWriter("c:\books1.xml", Nothing)
      w.Formatting = Formatting.Indented
      w.WriteProcessingInstruction("xml", "version=""1.0""")
      f.Serialize(w, RTofx)
      w.Close()

当然,OFXg类是XMLSerializable

答案 2 :(得分:1)

为什么你认为标题中有自定义属性?

WriteStartDocument使用或不使用独立属性写入标头。您的代码会添加您所说的合作伙伴不接受的属性。

您没有显示用于生成“utf-16”的代码,但我怀疑它写入了StringWriter。 .NET中的字符串总是UNICODE,当你写一个字符串时,你总是得到utf-16。如果您写入流,则可以控制编码。

答案 3 :(得分:0)

Necromancing。

您可以创建自己的XmlTextWriter并覆盖WriteStartDocument。

示例:

public class XmlTextWriterIndentedStandaloneNo : System.Xml.XmlTextWriter
{

    public bool bStandAlone = false;
    public bool bWriteStartDocument = true;
    public bool bOmitEncodingAndStandAlone = true;


    public XmlTextWriterIndentedStandaloneNo(System.IO.TextWriter w)
        : base(w)
    {
        Formatting = System.Xml.Formatting.Indented;
    } // End Constructor 


    public XmlTextWriterIndentedStandaloneNo(string strFileName, System.Text.Encoding teEncoding)
        : base(strFileName, teEncoding)
    {
        Formatting = System.Xml.Formatting.Indented;
    } // End Constructor 


    public XmlTextWriterIndentedStandaloneNo(System.IO.Stream w, System.Text.Encoding teEncoding)
        : base(w, teEncoding)
    {
        Formatting = System.Xml.Formatting.Indented;
    } // End Constructor 


    public override void WriteStartDocument(bool standalone)
    {
        if (bWriteStartDocument)
        {
            if (bOmitEncodingAndStandAlone)
            {
                this.WriteProcessingInstruction("xml", "version='1.0'");
                return;
            } // End if (bOmitEncodingAndStandAlone) 

            base.WriteStartDocument(bStandAlone);
        }

    } // End Sub WriteStartDocument 


    public override void WriteStartDocument()
    {
        // Suppress by ommitting WriteStartDocument
        if (bWriteStartDocument)
        {

            if (bOmitEncodingAndStandAlone)
            {
                this.WriteProcessingInstruction("xml", "version='1.0'");
                return;
            } // End if (bOmitEncodingAndStandAlone)

            base.WriteStartDocument(bStandAlone);
            // False: Standalone="no"
        } // End if (bWriteStartDocument)

    } // End Sub WriteStartDocument 


} // End Class XmlTextWriterIndentedStandaloneNo 

VB.NET

Public Class XmlTextWriterIndentedStandaloneNo
    Inherits System.Xml.XmlTextWriter

    Public bStandAlone As Boolean = False
    Public bWriteStartDocument As Boolean = True
    Public bOmitEncodingAndStandAlone As Boolean = True


    Public Sub New(w As System.IO.TextWriter)
        MyBase.New(w)
        Formatting = System.Xml.Formatting.Indented
    End Sub
    ' End Constructor 

    Public Sub New(strFileName As String, teEncoding As System.Text.Encoding)
        MyBase.New(strFileName, teEncoding)
        Formatting = System.Xml.Formatting.Indented
    End Sub
    ' End Constructor 

    Public Sub New(w As System.IO.Stream, teEncoding As System.Text.Encoding)
        MyBase.New(w, teEncoding)
        Formatting = System.Xml.Formatting.Indented
    End Sub
    ' End Constructor 

    Public Overrides Sub WriteStartDocument(standalone As Boolean)
        If bOmitEncodingAndStandAlone Then
            Me.WriteProcessingInstruction("xml", "version='1.0'")
            Return
        End If
        ' End if (bOmitEncodingAndStandAlone) 
        If bWriteStartDocument Then
            MyBase.WriteStartDocument(bStandAlone)
        End If
    End Sub
    ' End Sub WriteStartDocument 

    Public Overrides Sub WriteStartDocument()
        If bOmitEncodingAndStandAlone Then
            Me.WriteProcessingInstruction("xml", "version='1.0'")
            Return
        End If
        ' End if (bOmitEncodingAndStandAlone)
        ' Suppress by ommitting WriteStartDocument
        If bWriteStartDocument Then
                ' False: Standalone="no"
            MyBase.WriteStartDocument(bStandAlone)
        End If
        ' End if (bWriteStartDocument)
    End Sub
    ' End Sub WriteStartDocument 

End Class
' End Class XmlTextWriterIndentedStandaloneNo 

用法示例:

//using (System.Xml.XmlTextWriter wr = new System.Xml.XmlTextWriter(System.IO.Path.Combine(strBasePath, "TestFile.xml"), System.Text.Encoding.UTF8))
//using (System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(System.IO.Path.Combine(strBasePath, "TestFile.xml"), xwsSettings))
using (System.Xml.XmlWriter wr = new XmlTextWriterIndentedStandaloneNo(System.IO.Path.Combine(strBasePath, "TestFile.xml"), System.Text.Encoding.UTF8))
{
    //wr.Formatting = System.Xml.Formatting.None; // here's the trick !

    xdoc.Save(wr);
    wr.Flush();
    wr.Close();
} // End Using wr

答案 4 :(得分:-1)

此:

XmlWriterSettings xmlWriterSettings 
    = new XmlWriterSettings { OmitXmlDeclaration = true, };

会给你这个:

<?xml version="1.0"?>