i am having trouble generating an xml string when i add a space name. This is how i want to generate my xml like
xml sample:
<Feedback xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Record>
<ID>2FAC636E-F96C-4465-9272-760BAF73C0DF</QRCodeID>
<SubID>10B5236C-47FD-468D-B88D-D789CA0C663A</SubmissionID>
<UserID>1</UserID>
<Page>1</Page>
</Record>
<Record>
<ID>219C462B-B874-4408-AFBA-CA727922D50F</QRCodeID>
<SubID>10B5236C-47FD-468D-B88D-D789CA0C663A</SubmissionID>
<UserID>1</UserID>
<Page>2</Page>
</Record>
</Feedback>
What my code looks like now:
XDocument xdoc = new XDocument(
new XElement("Feedback xmlns:i='http://www.w3.org/2001/XMLSchema-instance'",
new XElement("Record",
new XElement("ID", idGuid),
new XElement("SubID", subGuid),
new XElement("UserID", 2),
new XElement("Page", pages)
)
)
);
when i run it throws an error here "Feedback xmlns:i='http://www.w3.org/2001/XMLSchema-instance'" that it doesn't like the character ' '
The documentation here suggests that something like the following should work:
XDocument xdoc = new XDocument(
new XElement("Feedback",
new XAttribute(XNamespace.Xmlns + "i", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(XNamespace.Xmlns + "j", "http://schemas.sitename.com/2013/03/Project.Models"),
new XElement("Record",
new XElement("ID", idGuid),
new XElement("SubID", subGuid),
new XElement("UserID", 2),
new XElement("Page", pages)
)
)
);
Have a look at this MSDN page, it explains everything you need to know
I'm pretty sure you need to use Namespaces.
This is trying to create a markup with your entire string, which is invalid.
Related
My XML file
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns="http://a01_data_navin"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://a01_data_navin event.xsd">
<Event>
<eventid>1</eventid>
<Photo>
<filepath>files\images\memory rep02.png</filepath>
<location>
<lat>35.496456056584158</lat>
<lon>-99.228515625</lon>
</location>
<datetimestamp>2020-03-29T00:00:00</datetimestamp>
</Photo>
</Event>
<Event>
<eventid>2</eventid>
<Photo>
<filepath>files\images\poop.jpeg</filepath>
<location>
<lat>36.137874718407268</lat>
<lon>-89.6044921875</lon>
</location>
<datetimestamp>2020-03-29T00:00:00</datetimestamp>
</Photo>
</Event>
</Root>
When i use XDocument in C#
XDocument xml = XDocument.Load(_xmlFilePath);
// create xml structure
var photo_XML = tempPhotoList.ToArray();
xml.Element("Root")?.Add(
new XElement("Event",
from photo in photo_XML
select new XElement("eventid", photo.EventId),
from photo1 in photo_XML
select new XElement("Photo",
new XElement("filepath", photo1.FileNameForPath),
new XElement("location",
new XElement("lat", photo1.GetLatitude()),
new XElement("lon", photo1.GetLongitude())),
new XElement("datetimestamp", photo1.DateTimeStamp)
))
);
When i run the above code i cant seem to enter into the xml file and iterate the tree. I would have to add a name space like this:
XDocument xml = XDocument.Load(_xmlFilePath);
// create xml structure
var photo_XML = tempPhotoList.ToArray();
xml.Element(NameSpace+"Root")?.Add(
new XElement("Event",
from photo in photo_XML
select new XElement("eventid", photo.EventId),
from photo1 in photo_XML
select new XElement("Photo",
new XElement("filepath", photo1.FileNameForPath),
new XElement("location",
new XElement("lat", photo1.GetLatitude()),
new XElement("lon", photo1.GetLongitude())),
new XElement("datetimestamp", photo1.DateTimeStamp)
))
);
With adding the Element(NameSpace+"Root"); im able to traverse through my xml file and add a new event but i end up with this..
<Event xmlns="">
<eventid>3</eventid>
<Photo>
<filepath>files\images\poop.jpeg</filepath>
<location>
<lat>17.140790393316649</lat>
<lon>1.7578125</lon>
</location>
<datetimestamp>2020-03-29T00:00:00</datetimestamp>
</Photo>
</Event>
I need some help on how to add or update a new event into an existing xml file which has namespace to deal with; using XDocument in C# ? It seems that using XDocument gets my task done.
Im stuck guys.. please help..
Try following :
XDocument xml = XDocument.Load(_xmlFilePath);
XElement root = xml.Root;
XNamespace ns = root.GetDefaultNamespace();
root.Add(new XElement(ns + "Event",
Hey everyone so this is what i did to resolve the issue in hand..
*I added namespace to every XElement instead of only at the root.. Sorry rookie mistake from before.. :P
XElement root = xml.Root;
XNamespace ns = root.GetDefaultNamespace();
root.Add(
new XElement(ns+"Event",
from photo in photo_XML
select new XElement(ns +"eventid", photo.EventId),
from photo1 in photo_XML
select new XElement(ns +"Photo",
new XElement(ns +"filepath", photo1.FileNameForPath),
new XElement(ns +"location",
new XElement(ns +"lat", photo1.GetLatitude()),
new XElement(ns +"lon", photo1.GetLongitude())),
new XElement(ns +"datetimestamp", photo1.DateTimeStamp)
))
);
I am trying to create xml file using XDcoument, but I am getting following error
Name cannot begin with the '<' character, hexadecimal value 0x3C
here is my code
XDocument d = new XDocument(
new XElement("<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'>",
new XElement("<S:Header xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'>",
new XElement("<ns13:ACASecurityHeader xmlns='urn:us:gov:treasury:irs:ext:aca:air:7.0' xmlns:ns10='urn:us:gov:treasury:irs:msg:acauibusinessheader' xmlns:ns11='http://www.w3.org/2000/09/xmldsig#' xmlns:ns12='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:ns13='urn:us:gov:treasury:irs:msg:acasecurityheader' xmlns:ns2='urn:us:gov:treasury:irs:common' xmlns:ns3='urn:us:gov:treasury:irs:msg:form1094-1095Btransmitterupstreammessage' xmlns:ns4='urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage' xmlns:ns5='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' xmlns:ns6='urn:us:gov:treasury:irs:msg:form1094-1095BCtransmittermessage' xmlns:ns7='urn:us:gov:treasury:irs:msg:form1094-1095BCtransmitterreqmessage' xmlns:ns8='urn:us:gov:treasury:irs:msg:irsacabulkrequesttransmitter' xmlns:ns9='urn:us:gov:treasury:irs:msg:acabusinessheader'>"),
new XElement("Author", "Moreno, Jordao")
),
new XElement("Book",
new XElement("Title", "Midieval Tools and Implements"),
new XElement("Author", "Gazit, Inbar")
)
),
new XComment("This is another comment."));
Can someone please help me on this?
here is sample XML file which I want to generate using XDocument
There is a much simpler way to do this rather than crafting the XML document by hand via XDocument, though I have an explanation and example below if you want to do it that way.
First, the simple way - create the XML as a string, and pass that string to XDocument.Parse, like this:
string xmlString = #"<S:Envelope xmlns:S=""http://schemas.xmlsoap.org/soap/envelope/""><S:Header xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd""><ns13:ACASecurityHeader xmlns:ns10=""urn:us:gov:treasury:irs:msg:acauibusinessheader"" xmlns:ns11=""http://www.w3.org/2000/09/xmldsig#"" xmlns:ns12=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"" xmlns:ns13=""urn:us:gov:treasury:irs:msg:acasecurityheader"" xmlns:ns2=""urn:us:gov:treasury:irs:common"" xmlns:ns3=""urn:us:gov:treasury:irs:msg:form1094-1095Btransmitterupstreammessage"" xmlns:ns4=""urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage"" xmlns:ns5=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" xmlns:ns6=""urn:us:gov:treasury:irs:msg:form1094-1095BCtransmittermessage"" xmlns:ns7=""urn:us:gov:treasury:irs:msg:form1094-1095BCtransmitterreqmessage"" xmlns:ns8=""urn:us:gov:treasury:irs:msg:irsacabulkrequesttransmitter"" xmlns:ns9=""urn:us:gov:treasury:irs:msg:acabusinessheader""><Author>Moreno, Jordao</Author><Book><Title>Midieval Tools and Implement</Title><Author>Gazit, Inbar</Author></Book></ns13:ACASecurityHeader><!--This is another comment--></S:Header></S:Envelope>";
XDocument xDoc2 = XDocument.Parse(xmlString);
xDoc2 will contain the XML you wish to send.
If you wish to do it the long way, then there are a couple of issues with your posted code.
First, you're not correctly handling the namespaces (the xmlns: attributes). Secondly, you're including the < and > in the call to XElement, and you don't need to do that - the method takes care of those two symbols.
What you need to do is to set up the namespaces, then add them to the appropriate elements as well as creating the attributes for them.
The sample code doesn't match the posted snippet, so I worked off your sample code to show you how to go about crafting the XML by hand.
XNamespace sNS = XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/");
XNamespace wsseNS = XNamespace.Get("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
XNamespace xmlnsNS = XNamespace.Get("urn:us:gov:treasury:irs:ext:aca:air:7.0");
XNamespace ns10NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:acauibusinessheader");
XNamespace ns11NS = XNamespace.Get("http://www.w3.org/2000/09/xmldsig#");
XNamespace ns12NS = XNamespace.Get("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
XNamespace ns13NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:acasecurityheader");
XNamespace ns2NS = XNamespace.Get("xmlns: ns2 = 'urn:us:gov:treasury:irs:common");
XNamespace ns3NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:form1094-1095Btransmitterupstreammessage");
XNamespace ns4NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage");
XNamespace ns5NS = XNamespace.Get("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
XNamespace ns6NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:form1094-1095BCtransmittermessage");
XNamespace ns7NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:form1094-1095BCtransmitterreqmessage");
XNamespace ns8NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:irsacabulkrequesttransmitter");
XNamespace ns9NS = XNamespace.Get("urn:us:gov:treasury:irs:msg:acabusinessheader");
XDocument xDoc = new XDocument(new XElement(sNS + "Envelope", new XAttribute(XNamespace.Xmlns + "S", sNS),
new XElement(sNS + "Header", new XAttribute(XNamespace.Xmlns + "wsse", wsseNS),
new XElement(ns13NS + "ACASecurityHeader", new XAttribute(XNamespace.Xmlns + "ns10", ns10NS),
new XAttribute(XNamespace.Xmlns + "ns11", ns11NS),
new XAttribute(XNamespace.Xmlns + "ns12", ns12NS),
new XAttribute(XNamespace.Xmlns + "ns13", ns13NS),
new XAttribute(XNamespace.Xmlns + "ns2", ns2NS),
new XAttribute(XNamespace.Xmlns + "ns3", ns3NS),
new XAttribute(XNamespace.Xmlns + "ns4", ns4NS),
new XAttribute(XNamespace.Xmlns + "ns5", ns5NS),
new XAttribute(XNamespace.Xmlns + "ns6", ns6NS),
new XAttribute(XNamespace.Xmlns + "ns7", ns7NS),
new XAttribute(XNamespace.Xmlns + "ns8", ns8NS),
new XAttribute(XNamespace.Xmlns + "ns9", ns9NS
new XAttribute("xmlns", xmlnsNS),
new XElement("Author", "Moreno, Jordao"),
new XElement("Book",
new XElement("Title", "Midieval Tools and Implement"),
new XElement("Author", "Gazit, Inbar"))
),
new XComment("This is another comment")
))
);
The first thing the above code does is sets up all the namespaces via XNamespace.
Next, the XML Document is constructed. The individual elements are created via XElement, with the various namespaces prefixed (i.e., new XElement(sNS + "Envelope",, and the other namespaces added via XAttribute.
Nesting can get tricky, so you have to be very careful doing it this way. The above code will produce the following XML:
<?xml version="1.0"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<ns13:ACASecurityHeader xmlns="urn:us:gov:treasury:irs:ext:aca:air:7.0"
xmlns:ns9="urn:us:gov:treasury:irs:msg:acabusinessheader"
xmlns:ns8="urn:us:gov:treasury:irs:msg:irsacabulkrequesttransmitter"
xmlns:ns7="urn:us:gov:treasury:irs:msg:form1094-1095BCtransmitterreqmessage"
xmlns:ns6="urn:us:gov:treasury:irs:msg:form1094-1095BCtransmittermessage"
xmlns:ns5="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:ns4="urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage"
xmlns:ns3="urn:us:gov:treasury:irs:msg:form1094-1095Btransmitterupstreammessage" xmlns:ns2="urn:us:gov:treasury:irs:common"
xmlns:ns13="urn:us:gov:treasury:irs:msg:acasecurityheader"
xmlns:ns12="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:ns11="http://www.w3.org/2000/09/xmldsig#"
xmlns:ns10="urn:us:gov:treasury:irs:msg:acauibusinessheader">
<Author>Moreno, Jordao</Author>
<Book>
<Title>Midieval Tools and Implement</Title>
<Author>Gazit, Inbar</Author>
</Book>
</ns13:ACASecurityHeader>
<!--This is another comment-->
</S:Header>
</S:Envelope>
What you're doing is a really hard way to do this. There is a much easier way.
You have the Xsd specifications from them, you can use the xsd command in the Visual Studio command line to generate C# objects that match the requirements automatically during serialization.
For the IRS ACA schemas, get all the XSD files into the same directory. Then in a sibling directory to the one you created, place the Common folder.
Then, in the command line navigate to the directory you created and put all the xsd files and run this command:
xsd /c IRS-EXT-ACA-AIR-7.0.xsd IRS-ACABulkRequestTransmitterMessage.xsd IRS-Form1094-1095CTransmitterUpstreamMessage.xsd IRS-CAC.xsd IRS-WSTimeStampElementMessage.xsd IRS-WSTimeStampElementMessage.xsd
You'll end up with a C# file that has almost 200 objects in it including all the enums and such necessary for generating data compliant with their specifications.
I'm new to L2XML and not altogether an expert at XML so it isn't surprising I'm having a little trouble. In my first step I'm declaring a relatively simple XDocument object to create a XML method result.
Here is a sample of the expected XML.
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<soap:Body>
<TXLife xmlns="http://ACORD.org/Standards/Life/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ACORD.org/Standards/Life/2 TXLife2.28enum.XSD">
<UserAuthResponse>
<TransResult>
<ResultCode tc="1">Success</ResultCode>
</TransResult>
<SvrDate>2010-12-02</SvrDate>
<SvrTime>14:40:50-06:00</SvrTime>
</UserAuthResponse>
<TXLifeResponse>
<TransRefGUID>V7504892456123812</TransRefGUID>
<TransType tc="121">General Requirement Order Request</TransType>
<TransExeDate>2010-12-02</TransExeDate>
<TransExeTime>14:40:50-06:00</TransExeTime>
<TransMode tc="2">Original</TransMode>
<TestIndicator tc="1">Yes</TestIndicator>
<TransResult>
<ResultCode tc="1">Success</ResultCode>
</TransResult>
<OLifE>
<SourceInfo>
<CreationDate>2010-12-02</CreationDate>
<CreationTime>14:40:50-06:00</CreationTime>
<SourceInfoName>External Vendor Name</SourceInfoName>
</SourceInfo>
</OLifE>
</TXLifeResponse>
</TXLife>
</soap:Body>
</soap:Envelope>
Here is the code I'm using to try to create something matching the above:
public string SubmitOrder121(string xmlIn)
{
string resultText = "SUCCESS"; //Hard coded for now. Needs to be set based on result of call to CrossBow.
string resultCode = "1"; //Same comment as above.
string date = DateTime.Today.ToShortDateString();
string time = DateTime.Now.ToShortTimeString();
string transRefGUID = "V7504892456123812"; //Hard coded for now. Get from xmlIn;
string transModeText = "Original"; //Don't know what this is for or where to get it if there are other possibilities
string transModeCode = "2"; //Same as above comment
string testIndicatorText = "True"; //Get from config file
string testIndicatorCode = "1"; //Get from config file
string companyName = "External Vendor Name"; //Get from config file
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace soap = "http://www.w3.org/2001/12/soap-envelope";
XNamespace xmlns = "http://ACORD.org/Standards/Life/2";
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", ""),
new XElement(soap + "Envelope",
new XAttribute(XNamespace.Xmlns + "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"),
new XAttribute(XNamespace.Xmlns + "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing"),
new XAttribute(XNamespace.Xmlns + "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"),
new XAttribute(XNamespace.Xmlns + "soap", "http://schemas.xmlsoap.org/soap/envelope/"),
new XElement(soap + "Body",
new XElement(xmlns + "TXLife",
new XAttribute(xsi + "schemaLocation", "http://ACORD.org/Standards"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XElement("UserAuthResponse",
new XElement("TransResult",
new XElement("ResultCode", resultText,
new XAttribute("tc", resultCode)
)
),
new XElement("SvrDate", date),
new XElement("SvrTime", time)
),
new XElement("TXLifeResponse",
new XElement("TransRefGUID", transRefGUID),
new XElement("TransType", "General Requiremeent Order Request",
new XAttribute("tc", "121")
),
new XElement("TransExeDate", date), //Get from crossbow result
new XElement("TransExeTime", time), //Get from crossbow result
new XElement("TransMode", transModeText,
new XAttribute("tc", transModeCode)
),
new XElement("TestIndicator", testIndicatorText,
new XAttribute("tc", testIndicatorCode)
),
new XElement("TransResult",
new XElement("ResultCode", resultText,
new XAttribute("tc", resultCode)
)
),
new XElement("OLife",
new XElement("SourceInfo",
new XElement("CreationDate", date),
new XElement("CreationTime", time),
new XElement("SourceInfoName", companyName)
)
)
)
)
)
)
);
return xdoc.ToString();
}
Now, given the little I've been able to understand so far, the above should give me what I want but it doesn't - exactly. It gives me this:
<Envelope xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://www.w3.org/2001/12/soap-envelope">
<Body>
<TXLife xsi:schemaLocation="http://ACORD.org/Standards" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ACORD.org/Standards/Life/2">
<UserAuthResponse xmlns="">
<TransResult>
<ResultCode tc="1">SUCCESS</ResultCode>
</TransResult>
<SvrDate>6/14/2013</SvrDate>
<SvrTime>1:57 PM</SvrTime>
</UserAuthResponse>
<TXLifeResponse xmlns="">
<TransRefGUID>V7504892456123812</TransRefGUID>
<TransType tc="121">General Requiremeent Order Request</TransType>
<TransExeDate>6/14/2013</TransExeDate>
<TransExeTime>1:57 PM</TransExeTime>
<TransMode tc="2">Original</TransMode>
<TestIndicator tc="1">True</TestIndicator>
<TransResult>
<ResultCode tc="1">SUCCESS</ResultCode>
</TransResult>
<OLife>
<SourceInfo>
<CreationDate>6/14/2013</CreationDate>
<CreationTime>1:57 PM</CreationTime>
<SourceInfoName>The Company Name</SourceInfoName>
</SourceInfo>
</OLife>
</TXLifeResponse>
</TXLife>
</Body>
</Envelope>
Ignore the date and time formats. I know they don't match but that is something I will concern myself with later, just as I will the hardcoded values. I'm more concerned with the XML format, particularly with the following:
Why isn't the XDeclaration appearing in the XML result?
On the Soap envelope and body, why isn't the soap prefix appearing?
How do I suppress the xmlns attribute on the and TXLifeResponse> tags?
I've already seen references in answers to other similar questions referring to this link:
http://msdn.microsoft.com/en-us/library/bb387042.aspx
but that wasn't much help to me.
The ToString() method never emits an XML declaration.
The reason why is a different story, but check with xdoc.Save("sample.xml"); that writes the declaration.
At the line XNamespace soap = "http://www.w3.org/2001/12/soap-envelope"; you probably have a typo, change it to http://schemas.xmlsoap.org/soap/envelope/
You have to specify default namespace for all the children of the TXLife element, like this:
new XElement(xmlns + "UserAuthResponse",
new XElement(xmlns + "TransResult",
new XElement(xmlns + "ResultCode", resultText,
new XAttribute("tc", resultCode)
Hope this helps
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to set the default XML namespace for an XDocument
I am trying to write a piece of code in Asp.net C#, in order to create a KML file on-the-fly and store it in a specific path.
The code gives an error when i want to add the xmlns="http://earth.google.com/kml/2.2" attribute of kml tag (see below). I tried replacing xmlns with another word like "id" and it works just fine. Does it have something to do with the word "xmlns" ??! pretty strange for me.
Please provide me a solution if you understand what the problem is... Thanks!
My code:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", ""),
new XComment("This is comment by me"),
new XElement("kml", new XAttribute("xmlns", "http://earth.google.com/kml/2.2"),
new XElement("Document",
new XElement("Name", "something"), new XElement("Placemark",
new XAttribute("id", "1"),
new XElement("title", "something"),
new XElement("description", "something"),
new XElement("LookAt",
new XElement("Longitude", "49.69"),
new XElement("Latitude", "32.345")), new XElement("Point", new XElement("Coordinates", "49.69,32.345,0"))))));
doc.Save(Server.MapPath(#"~\App_Data\markers.xml"));
The runtime error it gives:
The prefix '' cannot be redefined from '' to
'http://earth.google.com/kml/2.2' within the same start element tag.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Xml.XmlException: The prefix '' cannot be
redefined from '' to 'http://earth.google.com/kml/2.2' within the same
start element tag.
The kml file i would LIKE to create:
<?xml version="1.0" encoding="utf-8"?>
<!--This is comment by me-->
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<Name>something</Name>
<Placemark id="1">
<title>something</title>
<description>something</description>
<LookAt>
<Longitude>49.69</Longitude>
<Latitude>32.345</Latitude>
</LookAt>
<Point>
<Coordinates>49.69,32.345,0</Coordinates>
</Point>
</Placemark>
</Document>
</kml>
Define the namespace first
XNamespace n = "http://earth.google.com/kml/2.2";
new XElement(n+"kml")//just do n+ for each underlying elements
Also your XML structure is wrong,it should be like
XNamespace n = "http://earth.google.com/kml/2.2";
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", ""),
new XComment("This is comment by me"),
new XElement(n+"kml",
new XElement(n+"Document",
new XElement(n+"Name", "something"), new XElement(n+"Placemark",
new XAttribute("id", "1"),
new XElement(n+"title", "something"),
new XElement(n+"description", "something"),
new XElement(n+"LookAt",
new XElement(n+"Longitude", "49.69"),
new XElement(n+"Latitude", "32.345")), new XElement(n+"Point", new XElement(n+"Coordinates", "49.69,32.345,0")))))
);
I am creating XML using Linq to XML and C#. It all works great except when I need to manually add in a row in the XML. This row is only added if I have a value to pass through to it, otherwise I just ignore the entire tag.
I use XElement.Load to load in the string of text that I store in a string but when I attach it to the XML it always puts in xmlns="" at the end of my tag.
Is there a way I can tell XElement.Load to use the existing namespace or to ignore it when putting in the string to the XML?
Ideally I just want my string to be included to the XML being created without extra tags being added.
Below is a sample of what I currently do:
string XMLDetails = null;
if (ValuePassedThrough != null)
XMLDetails = "<MyNewTag Code=\"14\" Value=\"" + ValuePassedThrough +"\"></MyNewTag>";
When I build up the XML I load the above string into my XML. It is here where xmlns="" is being added to the XMLDetails value but ideally I want this ignored as it is causing issues with the recipient when they try 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 just the MyNewTag tag I load in using XElement.Load gets xmlns="" added to the end of it which is causing me an issue.
Any ideas how I can work around this? Thanks for your help.
Regards,
Rich
How about:
XElement withoutNamespace = XElement.Load(new StringReader(XMLDetails));
XElement withNamespace = new XElement(ns + withoutNamespace.Name.LocalName,
withoutNamespace.Nodes());
As a better alternative - why don't you either include the namespace when you're building up the XML, or even better, create an XElement instead of manually generating an XML string which you then read. Manually creating XML is very rarely a good idea. Aside from anything else, you're assuming that ValuePassedThrough has already been escaped, or doesn't need escaping etc. That may be valid - but it's at least a cause for concern.
Like this
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));