How to add (or ignore) the XML namespace when using XElement.Load

I am creating XML using Linq for XML and C #. All of this works fine, except when I need to manually add a string to XML. This line is added only if I have a value for passing it, otherwise I just ignore the entire tag.

I use XElement.Load to load a string of text that I store in a string, but when I attach it to XML, it is always placed at xmlns = "" at the end of my tag.

Is there any way XElement.Load can use an existing namespace or ignore it when entering a string in XML?

Ideally, I just want my string to be included in the generated XML without adding additional tags.

The following is an example of what I'm doing now:

string XMLDetails = null;
if (ValuePassedThrough != null)
XMLDetails = "<MyNewTag Code=\"14\" Value=\"" + ValuePassedThrough +"\"></MyNewTag>";

When I create the XML, I load the above line into my XML. This is where xmlns = "" is added to the XMLDetails value, but ideally I want it to be ignored, as it causes problems with the recipient when trying to read this tag.

XNamespace ns = "http://namespace-address";
    XNamespace xsi = "http://XMLSchema-instance-address";

XDocument RequestDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement(ns + "HeaderTag",
        new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", "http://www.addressofschema.xsd"),
        new XAttribute("Version", "1"),
            new XElement(ns + "OpeningTAG",

... my xml code ...

XElement.Load(new StringReader(XMLDetails))

... End of XML Code ...

As mentioned above. My code works, it successfully outputs XML for me. Its only the MyNewTag tag, which I load using XElement.Load, adds xmlns = "" to the end, which causes me a problem.

Any ideas how I can get around this? Thank you for your help.

Regards, Rich

+3
source share
2 answers

What about:

XElement withoutNamespace = XElement.Load(new StringReader(XMLDetails));
XElement withNamespace = new XElement(ns + withoutNamespace.Name.LocalName,
                                      withoutNamespace.Nodes());

- XML XElement , XML, . XML . , ValuePassedThrough .. , .

+7

XElement XMLDetails = new XElement(ns + "OpeningTAG", new XElement(ns + "MyNewTag", new XAttribute("Code", 14), new XAttribute("Value", 123)));

XDocument RequestDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement(ns + "HeaderTag",
        new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", "http://www.addressofschema.xsd"),
        new XAttribute("Version", "1"),
            XMLDetails));
+1

Source: https://habr.com/ru/post/1718164/


All Articles