How to remove the XML declaration when using LINQ to XML? - c#

i have a LINQ query like this, i need to remove the XML Declaration tag which is getting added automatically.
var cubbingmessagexml = new XDocument(
new XElement("MESSAGE", new XAttribute("ID", "CUB"),
new XElement("RECORD", new XAttribute("STORENO", cubing.StoreID),
new XAttribute("TPNB", cubing.ProductCode),
new XAttribute("QUANTITY", cubing.Quantity),
new XAttribute("CUBINGTIME", cubing.CubingDateTime.ToString("yyyyMMddHHmmss")),
new XAttribute("SHELFFACING", cubing.ShelfFacing)
)));
xml = cubbingmessagexml.ToString();
pls help
I dont want to save the XML file, just need to return the XML as a string

If you are referring the xml version and stuff at the top, there is an xml writer setting to turn that off.
var writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
using (var buffer = new StringWriter())
using (var writer = XmlWriter.Create(buffer, writerSettings))
{
cubbingmessagexml.Save(writer);
writer.Flush();
string result = buffer.ToString();
}

Skip the XDocument:
var cubbingmessagexml =
new XElement("MESSAGE", new XAttribute("ID", "CUB"),
new XElement("RECORD",
new XAttribute("STORENO", cubing.StoreID),
new XAttribute("TPNB", cubing.ProductCode),
new XAttribute("QUANTITY", cubing.Quantity),
new XAttribute("CUBINGTIME", cubing.CubingDateTime.ToString("yyyyMMddHHmmss")),
new XAttribute("SHELFFACING", cubing.ShelfFacing)
)
);
xml = cubbingmessagexml.ToString();
From MSDN:
Note that you only have to create XDocument objects if you require the specific functionality provided by the XDocument class. In many circumstances, you can work directly with XElement. Working directly with XElement is a simpler programming model.
and
As previously mentioned, the XElement class is the main class in the LINQ to XML programming interface. In many cases, your application will not require that you create a document. By using the XElement class, you can create an XML tree, add other XML trees to it, modify the XML tree, and save it.
Even with XDocument the declaration is not displayed.

Related

Token EndDocument in state Document would result in an invalid XML document when using .Save()

I'm writing an XML file using C# and Linq but when trying to save it gives me the 'Token EndDocument in state Document would result in an invalid XML document' error. The code for the creation and saving of the document:
XDocument xDoc = new XDocument();
using (var db = new CarRentalEntities1())
{
foreach (Car c in db.Cars)
{
XElement root = new XElement("root",
new XElement
(
"Car-" + c.CarName,
new XAttribute("CarID", c.CarID),
new XAttribute("CarName", c.CarName),
new XAttribute("CarType", c.CarType),
new XAttribute("Reg", c.Registration),
new XAttribute("YearOfPurchase", c.YearOfPurchase)
)
);
}
xDoc.Save("D:\\Cars.XML");
}
You're not adding anything to xDoc, so you're saving an empty XDocument to the file.
From #MarcinJuraszek comment above.

Convert object model to XML

Good day guys, How can i convert an object model to an xmldocument. this is my object:
var profile = new ProfileModel()
{
xh="aa",
FirstName = "wolverine",
LastName = "wolverine2",
PhoneNumber = "66332214477",
Email = "wolverine#wolverine.com",
SourceSystem = "TY",
ID = "ty1002224"
};
right now I'm doing it manually like this:
XDocument doc = new XDocument(new XElement("aa",
new XElement("FirstName","wolverine2"),
new XElement("LastName", "wolverine"),
new XElement("PhoneNumber", "66332214477"),
new XElement("Email", "wolverine#wolverine.com"),
new XElement("SourceSystem", "TY"),
new XElement("ID", "ty1002224")
));
but i want something more generic so i could use it to all of my object. Also, I have a case that I have a list of ProfileModel and need to convert it to xmldocument.
EDIT:
I want the output to be plain xdocument:
<aa>
<FirstName>wolverine2</FirstName>
<LastName>wolverine</LastName>
<PhoneNumber>66332214477</PhoneNumber>
<Email>wolverine#wolverine.com</Email>
<SourceSystem>TY</SourceSystem>
<ID>ty1002224</ID>
</aa>
Have a look at the XmlSerializer class
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
By using the amazing XDocument class. This will use reflection and serialize all the properties.
// in System.Xml.Linq
XDocument doc = new XDocument();
using (var writer = doc.CreateWriter())
{
// write xml into the writer
var serializer = new DataContractSerializer(objToSerialize.GetType());
serializer.WriteObject(writer, objectToSerialize);
}
Console.WriteLine(doc.ToString());
Source: How do I serialize an object into an XDocument?

Enter line-breaks / carriage returns between the XAttributes in a XElement.ToString result

Is there no way to get line-breaks to appear between attributes in the XElement.ToString resultant xml string?
The following didn't work -- it kept the line-breaks, but put them below all the attributes, so there were just 4/5 empty lines:
new XElement("options", new XText("\r\n"),
new XAttribute("updated", Updated.XmlTime()), new XText("\r\n"),
new XAttribute("color", Color), new XText("\r\n"),
new XAttribute("puppies", Puppies), new XText("\r\n"),
new XAttribute("isTrue", IsTrue), new XText("\r\n"),
new XAttribute("kitties", Kitties ?? "")),
You can do it using a XmlWriter. Try this:
public static string ToStringFormatted(this XElement xml)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
StringBuilder result = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(result, settings)) {
xml.WriteTo(writer);
}
return result.ToString();
} // ToStringFormatted
then
var xml =new XElement("options",
new XAttribute("updated", "U"),
new XAttribute("color", "C"),
new XAttribute("puppies", "P"),
new XAttribute("isTrue", "I"),
new XAttribute("kitties", "K")
);
Console.WriteLine(xml.ToStringFormatted());
produces this:
<options
updated="U"
color="C"
puppies="P"
isTrue="I"
kitties="K" />
You can have different formatting using the various XmlWriterSettings properties.
There is no way to put new lines inside XML object because there is no "text nodes" in XML DOM between attributes. All attributes for each node are in on big unordered* table and there is no "text-only" attributes.
Only text representation of XML can have such formatting of attributes. Note that all formatting between attributes will be lost on when such XML loaded in DOM/reader.
What you may be able to do is implement your own XmlWriter with formatting you want.
*) most XML DOM implementations keep order of attributes as in source or order they are added, but there is no requirement to do so.

Xml with two attributes in C#

I want to make xml element like this:
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut>
Now I'm doing this in this way:
XmlNode xmlAtrybutNode = xmlDoc.CreateElement("ElementName ");
_xmlAttr = xmlDoc.CreateAttribute("Type");
_xmlAttr.Value = "FirstAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);
_xmlAttr = xmlDoc.CreateAttribute("Name");
_xmlAttr.Value = "SecondAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);
xmlAtrybutNode.InnerText = !string.IsNullOrEmpty(Value)
? SetTextLength(Name, ValueLength)
: string.Empty;
Value is input variable in method.
Is there possibility to make this in another way?
More efficiently?
Can I use xmlWriter? Now i'm using xmlDocument.
You can use Linq to XML.
Basically
XDocument doc = new XDocument();
doc.Add(
new XElement("ElementName", "Value",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute")));
will give this xml document
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>
How about tweaking your existing code:
XmlElement el = xmlDoc.CreateElement("ElementName");
el.SetAttribute("Type", "FirstAttribute");
el.SetAttribute("Name", "SecondAttribute");
el.InnerText = ...;
Additional thoughts:
XElement
XmlSerializer (from a class instance)
If you’re on .NET 3.5 (or later), you could use LINQ to XML. Make sure that the System.Xml.Linq assembly is referenced, and that you have a using directive for its eponymous namespace.
XDocument document = new XDocument(
new XElement("ElementName",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute"),
value));
If you subsequently want to write the XDocument to a target, you can use its Save method. For debugging, it’s useful to call its ToString method, which returns its XML representation as a string.
Edit: Replying to comment:
If you need to convert the XDocument created above into an XmlDocument instance, you may use code similar to the following:
XmlDocument xmlDocument = new XmlDocument();
using (XmlReader xmlReader = document.CreateReader())
xmlDocument.Load(xmlReader);
What about using LINQ to XML as in this article. That can be very elegant - it can all be done on one line.
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("element",
new XAttribute("attribute1", "val1"),
new XAttribute("attribute2", "val2"),
)
);

How do I dynamically create an XML schema in C#?

I try to dynamically create an XML schema (XSD) from C#, using the conventional XElement and XAttribute classes, but it is not valid to specify any names with colons. That is, I cannot create the element <xs:element> using the code
... = new XElement("xs:element");
because ":" is not allowed.
What is the correct way of dynamically building a schema in C# then?
To create schemas, you should be using the XmlSchema class. The link below provides a comprehensive example of creating one programmatically:
http://msdn.microsoft.com/en-us/library/9ta3w88s.aspx
Example:
static void Main(string[] args)
{
var schema = new XmlSchema();
// <xs:element name="myElement" type="xs:string"/>
var myElement = new XmlSchemaElement();
schema.Items.Add(myElement);
elementCat.Name = "myElement";
elementCat.SchemaTypeName =
new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
// writing it out to any stream
var nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
schema.Write(Console.Out, nsmgr);
Console.ReadLine();
}
When creating new XML elements, you should be aware that the part before the colon (in this case, xs) is actually an alias for the XML namespace (in the case of an XSD, xs usually refers to http://www.w3.org/2001/XMLSchema). So, to continue using XDocument to build your XSD, you would want to use:
XNamespace ns = new XNamespace("http://www.w3.org/2001/XMLSchema");
... = new XElement(ns + "element");
See the example here:
http://msdn.microsoft.com/en-us/library/bb292758.aspx
I wrote a blog about that very subject. You can use a DataTable to save a schema.
If you want to create xml, you should use XmlWriter class

Categories