Linq XML problems using namespace . net

Asked

Viewed 68 times

0

I am using a namespace at the moment I create my xml, but xmlns is also appearing in the tag below the root, this is hurting me, how can I make 'xmlns' get apernas in the root tag (Tlote_gnre)? Follows the code:

Dim xDoc As New XDocument(New XDeclaration("1.0", "utf-8", Nothing))
Dim nS As XNamespace = "http://www.gnre.pe.gov.br"

Dim xGuias As XElement = New XElement("guias")
xDoc.Add(New XElement(nS + "TLote_GNRE", xGuias))

Dim sw As New StringWriter()
Dim xWrite As XmlWriter = XmlWriter.Create(sw)

xDoc.Save(xWrite)
xWrite.Close()

xDoc.Save("C:\xml.xml")

XML output:

<?xml version="1.0" encoding="UTF-8"?>
 <TLote_GNRE xmlns="http://www.gnre.pe.gov.br">
 <guias xmlns=""/>
</TLote_GNRE>

1 answer

1

Removing the variable nS from here:

xDoc.Add(New XElement(nS + "TLote_GNRE", xGuias))

I think it was confusing the way you used it. The right thing would be to use it like this:

Dim raiz As XElement = New XElement("TLote_GNRE", new XAttribute("Xmlns", ns))

Dim xGuias As XElement = New XElement(ns + "guias")
raiz.Add(xGuias)
xDoc.Add(raiz)

Note that "guias" also needs the namespace.

  • so, but the 'guides' tag is the daughter of the 'Tlote_gnre' tag, and the 'Tlote_gnre' tag needs the namespace I quoted.

  • So, but then you just pass the namespace pro root element, not child element.

  • I gave an improved answer that I think was not clear enough. See now.

  • I understand what you mean now, but there is an error in the moment that xNamespace.Xmlns. " System.xml.Linq.Xnamespace value cannot be converted to 'System.xml.Linq.Xname'."

  • Try to change XNamespace.Xmlns for "xmlns". Anything updates the answer.

  • I used xmlns as string, but the xml output is identical to the one I mentioned, the 'tabs' tag still leaves with xmlns

  • You’re right. I ate ball. "guides" also needs the namespace. Look now.

  • Friend, I think we’re talking about different things, the problem I’m trying is that in the tag daughter 'guides' is appearing the 'xmlns' and I want to leave it only at root, so I know that everything that comes after belongs to that namespace and so I can validate in Webservice, I say this because I’ve done some tests here the way I’m talking, but I did the xml on the nail

  • So, but the child element needs to be the same namespace of the parent element (in its case, the root), otherwise the interpreter thinks that the child element belongs to another namespace. You tested now with this my latest edition?

  • I understood, the way you did the namespace really entered the tag daughter, but then I have to continue this xml, and I can’t find the tag daughter as <guides>, but without namespace I find, I do the following to find: 'xDoc.Elements. <guides>(0)'

  • Well, then I guess that would be a question for another question.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.