更改xml命名空间(VB)

时间:2016-07-27 20:24:31

标签: .net vb.net xml-namespaces

我正在尝试创建一个XML文档。 我已经成功创建了文档但是我似乎无法弄清楚如何将默认的xmlns更改为其他内容。 这是我的代码

Imports System.Xml

Public Class Form1  

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim writer As New XmlTextWriter("product.xml", System.Text.Encoding.UTF8)
        writer.WriteStartDocument(True)
        writer.Formatting = Formatting.Indented
        writer.Indentation = 2
        writer.WriteStartElement("_-SAPMP_-PPCC2PRETT01")
        writer.WriteStartElement("IDOCBEGIN", 1)
        createNode("00B-021-5088", "BRL1", "KG", "1000", writer)
        writer.WriteEndElement()
        writer.WriteEndDocument()
        writer.Close()
    End Sub
    Private Sub createNode(ByVal pID As String, ByVal pName As String, ByVal pName2 As String, ByVal pPrice As String, ByVal writer As XmlTextWriter)
        writer.WriteStartElement("E1BP_PP_TIMETICKET", "E1BP_PP_TIMETICKET")
        writer.WriteStartElement("ORDERID")
        writer.WriteString(pID)
        writer.WriteEndElement()
        writer.WriteStartElement("PLANT")
        writer.WriteString(pName)
        writer.WriteEndElement()
        writer.WriteStartElement("CONF_QUAN_UNIT")
        writer.WriteString(pName2)
        writer.WriteEndElement()
        writer.WriteStartElement("YIELD")
        writer.WriteString(pPrice)
        writer.WriteEndElement()
        writer.WriteEndElement()
    End Sub

End Class

这会产生以下XML文件:

not expected

我希望它看起来像是:

expected

2 个答案:

答案 0 :(得分:0)

WriteStartElement的第二个参数是命名空间,而不是属性。您应该使用WriteAttributeString来写出元素的属性。所以,一些改变可以让你得到你想要的东西:

'...
writer.WriteStartElement("IDOC")
writer.WriteAttributeString("BEGIN", "1")
'...
writer.WriteStartElement("E1BP_PP_TIMETICKET")
writer.WriteAttributeString("SEGMENT", "E1BP_PP_TIMETICKET")

答案 1 :(得分:0)

如果我正确地阅读了您的问题,您需要做的就是添加以下内容:

writer.Namespaces = false;

https://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.namespaces(v=vs.110).aspx