XML Name Space Not Formating Correctly - c#

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"))

Related

How to add Namespace and Declaration in XDocument

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")))

XML XElement building an xml document

Hi I am new to XML building, I basically didn't use it before, I always preferred json.
I have a solution where I just make it with string and convert to XML object, but how can I do it with XElement class?
This is the document:
<?xml version="1.0" encoding="utf-8"?>
<requestblock version="3.67">
<alias>ALIAS</alias>
<request type="AUTH">
<operation>
<sitereference>test12345</sitereference>
<accounttypedescription>TEST</accounttypedescription>
<parenttransactionreference>12-3-4567</parenttransactionreference>
</operation>
<merchant>
<orderreference>Example recurring auth</orderreference>
</merchant>
<customer> </customer>
<billing>
<amount currencycode="GBP">1234</amount>
<subscription type="TEST">
<number>1</number>
</subscription>
</billing>
<settlement/>
</request>
</requestblock>
I already have a part of the code like this:
XElement address =
new XElement("alias", "TEST",
new XElement("request", new XAttribute("type", "AUTH"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
));
But I have a problem with alias, because alias is closed after all elements, not in the same notation:
<alias>TEST
<request type="AUTH">
<City>Mercer Island</City>
<State>WA</State>
<Postal>68042</Postal>
</request>
</alias>
As you can see notation is the problem.
You're setting alias as your root element, which should be requestblock. If you start with requestblock like this:
XElement address =
new XElement("requestblock", new XAttribute("version",3.67),
new XElement("alias", "TEST"),
new XElement("request", new XAttribute("type", "AUTH"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
It'l give you
<requestblock version="3.67">
<alias>TEST</alias>
<request type="AUTH">
<City>Mercer Island</City>
<State>WA</State>
<Postal>68042</Postal>
</request>
</requestblock>

how to handle namespaces in the root element

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).

Get custom attribute value using LINQ to XML

I'm writing to an XML file from which I'm going to retrieve data later.
Here's how I'm writing to the file.
XNamespace testNM = "urn:lst-emp:emp";
XDocument xDoc;
string path = "project_data.xml";
if (!File.Exists(path))
{
xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(testNM + "Test")
);
}
else
{
xDoc = XDocument.Load(path);
}
var element = new XElement("key",
new XAttribute("name", key),
new XElement("Type", type),
new XElement("Value", value));
xDoc.Element(testNM + "Test").Add(element);
// Save to Disk
xDoc.Save(path);
And this is what my XML file looks like after data is written to it.
<?xml version="1.0" encoding="utf-16"?>
<Test xmlns="urn:lst-emp:emp">
<key name="key2" xmlns="">
<Type>int</Type>
<Value>12312</Value>
</key>
<key name="key3" xmlns="">
<Type>String</Type>
<Value>asdfasd</Value>
</key>
</Test>
Now what would be the simplest way to get the name attribute value (key2 and key3 in this case) along with the Type and Value attribute values.
Load the document;
XDocument doc = XDocument.Load(#"doc.xml");
Loop the key nodes reading what you need;
foreach (var keyNode in doc.Root.Elements("key"))
{
var name = keyNode.Attribute("name");
var type = (string)keyNode.Element("Type"); // or .value to throw if there is no node
...
}

How do I get rid of empty namespaces "xmlns=""" in subelements?

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.

Categories