I have this
XNamespace ns = "http://something0.com";
XNamespace xsi = "http://something1.com";
XNamespace schemaLocation = "http://something3.com";
XDocument doc2 = new XDocument(
new XElement(ns.GetName("Foo"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi.GetName("schemaLocation"), schemaLocation),
new XElement("ReportHeader", GetSection()),
GetGroup()
)
);
It gives
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://something1.com"
xsi:schemaLocation="http://something3.com"
xmlns="http://something0.com">
<ReportHeader xmlns="">
...
</ReportHeader>
<Group xmlns="">
...
</Group>
</Foo>
But I wan't this result, how can it be done? (Notice the xmlns=""is missing..)
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://something1.com"
xsi:schemaLocation="http://something3.com"
xmlns="http://something0.com">
<ReportHeader>
...
</ReportHeader>
<Group>
...
</Group>
</Foo>
Your problem here is that you are setting the default namespace for the document to "http://something0.com", but then appending elements that are not in this namespace - they are in the empty namespace.
Your document states it has a default namespace of xmlns="http://something0.com", but then you append elements which are in the empty namespace (because you didn't supply their namespace when you appended them) - so they are all getting explicitly marked with xmlns='' to show they are not in the default namespace of the document.
This means there are two solutions to getting rid of the xmlns="", but they have different meanings:
1) If you mean you definitely want the xmlns="http://something0.com" at the root element (specifying the default namespace for the document) - then to "disappear" the xmlns="" you need to you need to supply this namespace when creating the elements:
// create a ReportHeader element in the namespace http://something0.com
new XElement(ns + "ReportHeader", GetSection())
2) If these elements are not meant to be in the namespace
"http://something0.com", then you mustn't add it as the default at
the top of the document (the xmlns="http://something0.com" bit on
the root element).
XDocument doc2 = new XDocument(
new XElement("foo", // note - just the element name, rather s.GetName("Foo")
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
The sample output you expect, suggests the former of these two choices.
Related
I am creating xml in C#, and want to add Namespace and Declaration . My xml as below:
XNamespace ns = "http://ab.com//abc";
XDocument myXML = new XDocument(
new XDeclaration("1.0","utf-8","yes"),
new XElement(ns + "Root",
new XElement("abc","1")))
This will add xmlns="" at both Root level and child element abc level as well.
<Root xmlns="http://ab.com/ab">
<abc xmlns=""></abc>
</Root>
But I want it in only Root level not in child level like below:
<Root xmlns="http://ab.com/ab">
<abc></abc>
</Root>
and how to add Declaration at Top, my code not showing Declaration after run.
Please help me to get the complete xml as
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Root xmlns="http://ab.com/ab">
<abc></abc>
</Root>
You need to use the same namespace in your child elements:
XDocument myXML = new XDocument(
new XDeclaration("1.0","utf-8","yes"),
new XElement(ns + "Root",
new XElement(ns + "abc", "1")))
If you just use "abc" this will be converted to an XName with no Namespace. This then results in an xmlns="" attribute being added so the fully qualified element name for abc would be resolved as such.
By setting the name to ns + "abc" no xmlns attribute will be added when converted to string as the default namespace of http://ab.com/ab is inherited from Root.
If you wanted to simply 'inherit' the namespace then you wouldn't be able to do this in such a fluent way. You'd have create the XName using the namespace of the parent element, for example:
var root = new XElement(ns + "Root");
root.Add(new XElement(root.Name.Namespace + "abc", "1"));
Regarding the declaration, XDocument doesn't include this when calling ToString. It will if you use Save to write to a Stream, TextWriter, or if you supply an XmlWriter that doesn't have OmitXmlDeclaration = true in its XmlWriterSettings.
If you wanted to just get the string, this question has an answer with a nifty extension method using a StringWriter.
Use the namespace on all elements you create:
XDocument myXML = new XDocument(
new XDeclaration("1.0","utf-8","yes"),
new XElement(ns + "Root",
new XElement(ns + "abc","1")))
I am reading from a csv file and transferring the data to an xml file using XmlSerializer in c#.But now I am facing a problem with the namespaces in the root element.My required xml should be in the following format.
<?xml version="1.0" encoding="ASCII"?>
<abc:Country xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:abc="some url">
<Person></Person>
</abc:Country>
But I am getting my output in this format:
<?xml version="1.0" encoding="ASCII"?>
<Country xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Person></Person>
</Country>
I want the namespace of abc to be included in the root and then also "abc" should prefix only my root element i.e "Country". I tried using various options mentioned online but none of them actually worked for me.When i use the XmlSerializerNamespaces and overload my Serialiser class all opther namespaces disappear.So could you let me know how I could achieve this.
Is it important to use XmlSerializer? This sort of thing is pretty easy to do with XDocument instead. Something like this:
var document = new XDocument();
XNamespace abcns = "http://some/url/abc";
XNamespace xmins = "http://www.omg.org/XMI";
XNamespace xsins = "http://www.w3.org/2001/XMLSchema-instance";
var element = new XElement(abcns + "Country",
new XAttribute(XNamespace.Xmlns + "abc", abcns),
new XAttribute(XNamespace.Xmlns + "xmi", xmins),
new XAttribute(XNamespace.Xmlns + "xsi", xsins),
new XAttribute(xmins + "version", "2.0"),
new XElement("Person"));
document.Add(element);
We can use the following to include multiple namespaces in the root element of the xml:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xmi", "http://www.omg.org/XMI");
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
ns.Add("abc", "some url");
XmlSerializer serializer = new XmlSerializer(typeof(Country));
TextWriter textWriter = new StreamWriter(#"C:\test.xml", true, Encoding.ASCII);
serializer.Serialize(textWriter, country, ns);
"country" would be the object that you would be creating for the class "Country"(root element of your xml).
Situation
I'm using XDocument to try and remove an xmlns="" attribute on the first inner node:
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
So what I want as a result is:
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
Code
doc = XDocument.Load(XmlReader.Create(inStream));
XElement inner = doc.XPathSelectElement("/*/*[1]");
if (inner != null)
{
inner.Attribute("xmlns").Remove();
}
MemoryStream outStream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(outStream);
doc.Save(writer); // <--- Exception occurs here
Problem
Upon trying to save the document, I get the following exception:
The prefix '' cannot be redefined from '' to 'http://my.namespace' within the same start element tag.
What does this even mean and what can I do to remove that pesky xmlns=""?
Notes
I do want to keep the root node's namespace
I only want that specific xmlns removed, there will be no other xmlns attributes in the document.
Update
I've tried using code inspired from answers on this question:
inner = new XElement(inner.Name.LocalName, inner.Elements());
When debugging, the xmlns attribute is gone from it but I get the same exception.
I think the code below is what you want. You need to put each element into the right namespace, and remove any xmlns='' attributes for the affected elements. The latter part is required as otherwise LINQ to XML basically tries to leave you with an element of
<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">
Here's the code:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml");
// All elements with an empty namespace...
foreach (var node in doc.Root.Descendants()
.Where(n => n.Name.NamespaceName == ""))
{
// Remove the xmlns='' attribute. Note the use of
// Attributes rather than Attribute, in case the
// attribute doesn't exist (which it might not if we'd
// created the document "manually" instead of loading
// it from a file.)
node.Attributes("xmlns").Remove();
// Inherit the parent namespace instead
node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
}
Console.WriteLine(doc); // Or doc.Save(...)
}
}
There is no need to 'remove' the empty xmlns attribute. The whole reason that the empty xmlns attrib is added is because the namespace of your childnodes is empty (= '') and therefore differ from your root node. Adding the same namespace to your childs as well will solve this 'side-effect'.
XNamespace xmlns = XNamespace.Get("http://my.namespace");
// wrong
var doc = new XElement(xmlns + "Root", new XElement("Firstelement"));
// gives:
<Root xmlns="http://my.namespace">
<Firstelement xmlns="" />
</Root>
// right
var doc = new XElement(xmlns + "Root", new XElement(xmlns + "Firstelement"));
// gives:
<Root xmlns="http://my.namespace">
<Firstelement />
</Root>
Building an XML XDocument to push to web service and the root element needs namespace values this is what the XML form should look like....
<shipment-feed xmlns="http://seller.marketplace.sears.com/oms/v5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://seller.marketplace.sears.com/oms/v5 asn.xsd ">
<shipment>
<header>
<asn-number>00601780002</asn-number>
<po-number>0060180</po-number>
<po-date>2009-09-26</po-date>
</header>
<detail>
<tracking-number>UPS1XXX</tracking-number>
<ship-date>2001-01-01</ship-date>
<shipping-carrier>UPS</shipping-carrier>
<shipping-method>GROUND</shipping-method>
<package-detail>
<line-number>1</line-number>
<item-id>AB12345678912345456789123456789CD</item-id>
<quantity>1</quantity>
</package-detail>
</detail>
</shipment>
</shipment-feed>
This is the xml that I'm getting....
<?xml version="1.0" encoding="utf-8"?>
<shipment-feed xmlns="http://seller.marketplace.sears.com/oms/v5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsischemalocation="http://seller.marketplace.sears.com/oms/v5 asn.xsd">
<shipment xmlns="">
<header>
<asn-number>2824565201311</asn-number>
<po-number>2824565</po-number>
<po-date>2013-11-14</po-date>
</header>
<details>
<tracking-number>579040914892</tracking-number>
<ship-date>2013-11-14</ship-date>
<shipping-carrier>FEDEX</shipping-carrier>
<shipping-method>Ground</shipping-method>
<package-details>
<line-number>1</line-number>
<item-id>LTH7XB1MW-EA</item-id>
<quantity>3</quantity>
</package-details>
</details>
</shipment>
<shipment xmlns="">
<header>
<asn-number>2821596201311</asn-number>
<po-number>2821596</po-number>
<po-date>2013-11-13</po-date>
</header>
<details>
<tracking-number>9405515901119923380663</tracking-number>
<ship-date>2013-11-14</ship-date>
<shipping-carrier>USPS</shipping-carrier>
<shipping-method>Priority Mail</shipping-method>
<package-details>
<line-number>1</line-number>
<item-id>CWD93151-EA</item-id>
<quantity>6</quantity>
</package-details>
<package-details>
<line-number>2</line-number>
<item-id>CWD93901-EA</item-id>
<quantity>4</quantity>
</package-details>
</details>
</shipment>
</shipment-feed>
This is the C# code I created....
XNamespace ns1 = "http://seller.marketplace.sears.com/oms/v5";
XNamespace ns2 = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace ns3 = "http://seller.marketplace.sears.com/oms/v5 asn.xsd";
XDocument doc = new XDocument();
XElement root = new XElement(ns1 + "shipment-feed",
new XAttribute("xmlns" , "http://seller.marketplace.sears.com/oms/v5"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute("xsi" + "schemalocation", "http://seller.marketplace.sears.com/oms/v5 asn.xsd"));
doc.Add(root);
int x = 1;
foreach (SearsOrder s in SearsList)
{
XElement shipment = new XElement("shipment",
new XElement("header",
new XElement("asn-number", s.asnnumber),
new XElement("po-number", s.ponumber),
new XElement("po-date", s.podate)),
new XElement("details",
new XElement("tracking-number", s.trackingnum),
new XElement("ship-date", s.shipdate),
new XElement("shipping-carrier", s.carrier),
new XElement("shipping-method", s.method),
s.orderitems.Select(i => new XElement("package-details",
new XElement("line-number", x++),
new XElement("item-id", i.itemid),
new XElement("quantity", i.quantity)))
));
doc.Root.Add(shipment);
x = 1;
}
The fist problem is the first child node I'm not seeing where that is coming from because that node is not even declared until the foreach loop. I was under the impression that I was only adding attributes to the root element.
and the other problem is removing the xml declaration
This sort of the thing is the problem:
new XElement("shipment", ...)
You want the shipment elements to be in the "http://seller.marketplace.sears.com/oms/v5" namespace - so you need to make that explicit. That won't show up in the resulting XML directly, because they'll inherit that as the default namespace specified in the root. Basically, wherever you're creating an element, you probably want to use ns1. So:
new XElement(ns1 + "shipment", new XElement(ns1 + "header", ...), ...)
To understand more about why this is required, you should read up on namespace defaulting in the XML Namespaces specification.
and the other problem is removing the xml declaration
So add an XDeclaration to the XDocument:
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"))
I am having trouble creating an XML document that contains a default namespace and a named namespace, hard to explain easier to just show what I am trying to produce...
<Root xmlns="http://www.adventure-works.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:SchemaLocation="http://www.SomeLocatation.Com/MySchemaDoc.xsd">
<Book title="Enders Game" author="Orson Scott Card" />
<Book title="I Robot" author="Isaac Asimov" />
</Root>
but what I end up with is this...
<Root xmlns="http://www.adventure-works.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:SchemaLocation="http://www.SomeLocatation.Com/MySchemaDoc.xsd">
<Book p3:title="Enders Game" p3:author="Orson Scott Card" xmlns:p3="http://www.adventure-works.com" />
<Book p3:title="I Robot" p3:author="Isaac Asimov" xmlns:p3="http://www.adventure-works.com" />
</Root>
The code that I wrote to produce this XML snippet is this...
XNamespace aw = "http://www.adventure-works.com";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XElement root = new XElement(aw + "Root",
new XAttribute("xmlns", "http://www.adventure-works.com"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "SchemaLocation", "http://www.SomeLocatation.Com/MySchemaDoc.xsd"),
new XElement(aw + "Book",
new XAttribute(aw + "title", "Enders Game"),
new XAttribute(aw + "author", "Orson Scott Card")),
new XElement(aw + "Book",
new XAttribute(aw + "title", "I Robot"),
new XAttribute(aw + "author", "Isaac Asimov")));
based on an example on MSDN
****EDIT****
Ok, with some more experimentation I am now very confused on how XML namespaces work....
if I remove the aw + theattribute I get what I was after...but now it seems that what I was after is not actually what I expected. I thought that namespaces were inherited from their parents, is this not true of attributes as well? because, this code to read the attributes does not work as I expected...
XElement xe = XElement.Parse(textBox1.Text);
XNamespace aw = "http://www.adventure-works.com";
var qry = from x in xe.Descendants(aw + "Book")
select (string)x.Attribute(aw + "author");
However if I remove the aw + on the attribute its ok, leading me to assume that I cannot have attributes in the default namespace. Is this correct?
Good question. I dug around a bit, and found this bit of the XML spec:
A default namespace declaration
applies to all unprefixed element
names within its scope. Default
namespace declarations do not apply
directly to attribute names; the
interpretation of unprefixed
attributes is determined by the
element on which they appear.
It later goes on to give this example:
For example, each of the bad empty-element tags is illegal in the following:
<!-- http://www.w3.org is bound to n1 and n2 -->
<x xmlns:n1="http://www.w3.org"
xmlns:n2="http://www.w3.org" >
<bad a="1" a="2" />
<bad n1:a="1" n2:a="2" />
</x>
However, each of the following is legal, the second because the default namespace does not > apply to attribute names:
<!-- http://www.w3.org is bound to n1 and is the default -->
<x xmlns:n1="http://www.w3.org"
xmlns="http://www.w3.org" >
<good a="1" b="2" />
<good a="1" n1:a="2" />
</x>
So basically, it looks like attribute names don't get namespaces by default, which explains everything you've seen :)
XElement doc = XElement.Parse(ToXml());
doc.DescendantsAndSelf().Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
var ele = doc.DescendantsAndSelf();
foreach (var el in ele)
el.Name = ns != null ? ns + el.Name.LocalName : el.Name.LocalName;
For anyone else who spent 2 days trying to find an answer.