Add a XmlNode with the namespace of the parent node in .Net

拟墨画扇 提交于 2019-12-11 01:28:49

问题


I am using XmlDocument and XmlNode to manipulate a xml file. Say I want to add a valid node called "Language" to the root, I use such code:

Dim languageNode As XmlNode = xmlDoc.CreateNode(XmlNodeType.Element, "Language", Nothing)
languageNode.InnerText = "en-US"
root.AppendChild(languageNode)

where xmlDoc is a XmlDocument object and has already been loaded. However, in the xml file after the operation, it appeas like this:

<Language xmlns="">en-US</Language>

And this doesn't pass the validation. Is there anyway to get rid of the namespace? Thanks!

Update: I am editing a .rdlc file, which defines a local report, and using xml format. Part of the file looks like this:

<?xml version="1.0" encoding="utf-16"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" 
xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

<Language xmlns="">en-US</Language>
...

Normally there shouldn't be so many namespaces in use but I am generating it from xslt. But the Language node is added after this file is generated. My code looks like this:

Dim xmlRdlc As New XmlDocument()
xmlRdlc.Load(file)    
Dim root As XmlNode = xmlRdlc.DocumentElement()
Dim languageNode As XmlNode = xmlRdlc.CreateNode(XmlNodeType.Element, "Language", Nothing)
languageNode.InnerText = "en-US"
root.AppendChild(languageNode)
xmlRdlc.Save(file)

So how should I do to add the desired node like this:

<Language>en-US</Language>

回答1:


You need to specify the namespace. Pass "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" as the last parameter to the method.

Dim xmlRdlc As New XmlDocument()
xmlRdlc.Load(file)    
Dim root As XmlNode = xmlRdlc.DocumentElement()
Dim languageNode As XmlNode = xmlRdlc.CreateNode(XmlNodeType.Element, "Language", _
    "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition")
languageNode.InnerText = "en-US"
root.AppendChild(languageNode)
xmlRdlc.Save(file)

BTW, this would be cleaner using LINQ to XML:

Dim rdlcNS As XNamespace = "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition"
Dim xmlRdlc = XDocument.Load(file)
xmlRdlc.Root.Add(New XElement(rdlcNS + "Language", "en-US"))
xmlRdlc.Save(file)

(translation to VB.NET approximate, your mileage may vary, etc.)



来源:https://stackoverflow.com/questions/7929969/add-a-xmlnode-with-the-namespace-of-the-parent-node-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!