我正在构建一个VB.net控制台应用程序,该应用程序读取SQL并构建XML。我正在使用Visual Studio 2013和.Net Framework 4.5。我的代码如下:
Private _namespaceDefault as String = ""AAIS_Homeowners_Premium""
Dim writer As XmlWriter = XmlWriter.Create(policyDir & "\Policy.xml", settings)
writer.WriteStartDocument()
writer.WriteStartElement("ROOT")
writer.WriteAttributeString("xmlns", "", Nothing, _namespaceDefault)
我也尝试过:
writer.WriteAttributeString("xmlns", _namespaceDefault)
当我运行程序时,出现以下错误:“前缀”不能在同一开始元素标记中从”重新定义为“ AAIS_Homeowners_Premium”。” xmlns值不是URL,而是用于验证的Schema文件的名称。
如何将xmlns属性值添加到开始元素? XML应该如下所示:
<?xml version="1.0"?>
<ROOT xmlns="AAIS_Homeowners_Premium">
<Company>12345</Company>
<LOB>ABCDEFG</LOB>
<Policies>
<Policy>
<PolicyNumber>6789</PolicyNumber>
<Date>01/24/2018</Date>
</Policy>
<Policy>
<PolicyNumber>2345</PolicyNumber>
<Date>03/17/2018</Date>
</Policy>
</Policies>
</ROOT>
谢谢。
答案 0 :(得分:0)
这是一些代码和输出。应该是您要寻找的:
代码:
Dim _namespaceDefault As String = "AAIS_Homeowners_Premium"
Dim doc As System.Xml.XmlDocument
Dim elm As System.Xml.XmlNode
Dim elmSub As System.Xml.XmlNode
Dim elmMain As Xml.XmlNode
doc = New Xml.XmlDocument
elmMain = doc.CreateElement("ROOT")
elmSub = elmMain.Attributes.Append(doc.CreateAttribute("xmlns"))
elmSub.Value = _namespaceDefault
elm = elmMain.AppendChild(doc.CreateElement("FirstNode"))
elm.InnerText = "12345"
elm = elmMain.AppendChild(doc.CreateElement("SecondNode"))
elm.InnerText = "ABCDEFG"
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", "no"))
doc.AppendChild(elmMain)
doc.Save("Policy.xml")
和结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ROOT xmlns="AAIS_Homeowners_Premium">
<FirstNode>12345</FirstNode>
<SecondNode>ABCDEFG</SecondNode>
</ROOT>
答案 1 :(得分:0)
这是使用代码进行操作的方式(尽管两者都很有用):
Dim _namespaceDefault As String = "AAIS_Homeowners_Premium"
Dim writer As Xml.XmlWriter = Xml.XmlWriter.Create("Policy.xml", settings)
writer.WriteStartDocument()
writer.WriteStartElement("ROOT", _namespaceDefault)
writer.WriteElementString("Company", "12345")
writer.WriteElementString("LOB", "ABCDEFG")
writer.WriteStartElement("Policies")
writer.WriteStartElement("Policy")
writer.WriteElementString("PolicyNumber", "6789")
writer.WriteElementString("Date", "01/24/2018")
writer.WriteEndElement() 'Policy
writer.WriteStartElement("Policy")
writer.WriteElementString("PolicyNumber", "2345")
writer.WriteElementString("Date", "03/17/2018")
writer.WriteEndElement() 'Policy
writer.WriteEndElement() 'Policies
writer.WriteEndElement() 'ROOT
writer.WriteEndDocument()
writer.Close()
writer = Nothing
,输出为
<?xml version="1.0" encoding="utf-8"?>
<ROOT xmlns="AAIS_Homeowners_Premium">
<Company>12345</Company>
<LOB>ABCDEFG</LOB>
<Policies>
<Policy>
<PolicyNumber>6789</PolicyNumber>
<Date>01/24/2018</Date>
</Policy>
<Policy>
<PolicyNumber>2345</PolicyNumber>
<Date>03/17/2018</Date>
</Policy>
</Policies>
</ROOT>