user1477388
user1477388

Reputation: 21440

Creating XML with LINQ in C#

I am trying to create the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload">
<operation>insert</operation>
<object>Contact</object>
<contentType>CSV</contentType>
</jobInfo>

I have the following code (just starting out):

XElement _obj = new XElement("?xml",
                new XAttribute("version", "1.0"),
                new XAttribute("encoding", "UTF-8")
                );

The error I get is:

Name cannot begin with the '?' character, hexadecimal value 0x3F.

I am new to creating XML with LINQ in C# and was just wondering if I am going about it the right way... How can I create the XML document I am trying to create?

Upvotes: 0

Views: 2072

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167716

XNamespace dl = "http://www.force.com/2009/06/asyncapi/dataload";
XElement jobInfo = new XElement(dl + "jobInfo",
  new XElement(dl + "operation", "insert"),
  new XElement(dl + "object", "Contact"),
  new XElement(dl + "contentType", "CSV")
);

jobInfo.Save("info.xml");

should do and write an XML declaration <?xml version="1.0" encoding="UTF-8"?> without any need to create it explicitly.

Upvotes: 1

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22814

You seem to be looking for an XDeclaration. These are automatically inserted, so you don't need to worry about them. If you really need it though:

XDeclaration _obj = new XDeclaration("1.0", "utf-8", "");

Upvotes: 3

Related Questions