Most votes on xml questions 9

Most votes on xml questions 9. #81 LINQ to read XML #82 How to apply an XSLT Stylesheet in C# #83 Converting XDocument to XmlDocument and vice versa #84 Format XML string to print friendly XML string #85 How to put space character into a string name in XML? #86 Error: The processing instruction target matching "[xX][mM][lL]" is not allowed #87 Convert XML String to Object #88 XPath: Get parent node from child node #89 What is the difference between Linq to XML Descendants and Elements #90 How to set RecyclerView app:layoutManager="" from XML?

Read all the top votes questions and answers in a single page.

#81: LINQ to read XML (Score: 204)

Created: 2009-03-22 Last updated: 2020-05-06

Tags: c#, xml, linq, linq-to-xml

I got this XML file:

	<level1 name="A">
        <level2 name="A1" />
        <level2 name="A2" />
	<level1 name="B">
        <level2 name="B1" />
        <level2 name="B2" />
	<level1 name="C" />

Could someone give me a C# code using LINQ, the simplest way to print this result:
(Note the extra space if it is a level2 node)


Currently I got this code:

XDocument xdoc = XDocument.Load("data.xml"));
var lv1s = from lv1 in xdoc.Descendants("level1")
           select lv1.Attribute("name").Value;

foreach (var lv1 in lv1s)

	var lv2s = from lv2 in xdoc...???

#81 Best answer 1 of LINQ to read XML (Score: 232)

Created: 2009-03-22 Last updated: 2019-07-18

Try this.

using System.Xml.Linq;

void Main()
    StringBuilder result = new StringBuilder();

    //Load xml
    XDocument xdoc = XDocument.Load("data.xml");

    //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
               select new { 
                   Header = lv1.Attribute("name").Value,
                   Children = lv1.Descendants("level2")
    //Loop through results
    foreach (var lv1 in lv1s){
            foreach(var lv2 in lv1.Children)
                 result.AppendLine("     " + lv2.Attribute("name").Value);

#81 Best answer 2 of LINQ to read XML(Score: 54)

Created: 2009-03-22

Or, if you want a more general approach - i.e. for nesting up to “levelN”:

void Main()
    XElement rootElement = XElement.Load(@"c:\events\test.xml");
    Console.WriteLine(GetOutline(0, rootElement));	

private string GetOutline(int indentLevel, XElement element)
    StringBuilder result = new StringBuilder();

    if (element.Attribute("name") != null)
        result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);

    foreach (XElement childElement in element.Elements())
        result.Append(GetOutline(indentLevel + 1, childElement));

    return result.ToString();

See also original question in stackoverflow

#82: How to apply an XSLT Stylesheet in C# (Score: 195)

Created: 2008-08-29 Last updated: 2012-01-18

Tags: c#, xml, xslt

I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.

#82 Best answer 1 of How to apply an XSLT Stylesheet in C# (Score: 181)

Created: 2008-08-29 Last updated: 2014-06-02

I found a possible answer here:

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;


But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);

#82 Best answer 2 of How to apply an XSLT Stylesheet in C#(Score: 140)

Created: 2012-05-15 Last updated: 2016-03-14

Based on Daren’s excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Transform("source.xml", "result.html"); 

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don’t even need a variable:

With New XslCompiledTransform()
    .Transform("source.xml", "result.html")
End With

See also original question in stackoverflow

#83: Converting XDocument to XmlDocument and vice versa (Score: 194)

Created: 2009-10-02

Tags: c#, xml, linq-to-xml

It’s a very simple problem that I have. I use XDocument to generate an XML file. I then want to return it as a XmlDocument class. And I have an XmlDocument variable which I need to convert back to XDocument to append more nodes.

So, what is the most efficient method to convert XML between XDocument and XmlDocument? (Without using any temporary storage in a file.)

#83 Best answer 1 of Converting XDocument to XmlDocument and vice versa (Score: 310)

Created: 2009-10-02 Last updated: 2010-05-20

You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

Putting that into an Extension method to make it easier to work with.

using System;
using System.Xml;
using System.Xml.Linq;

namespace MyTest
    internal class Program
        private static void Main(string[] args)

            var xmlDocument = new XmlDocument();

            var xDocument = xmlDocument.ToXDocument();
            var newXmlDocument = xDocument.ToXmlDocument();

    public static class DocumentExtensions
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            return xmlDocument;

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
            using (var nodeReader = new XmlNodeReader(xmlDocument))
                return XDocument.Load(nodeReader);


#83 Best answer 2 of Converting XDocument to XmlDocument and vice versa(Score: 28)

Created: 2012-02-21

For me this single line solution works very well

XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument

See also original question in stackoverflow

#84: Format XML string to print friendly XML string (Score: 193)

Created: 2009-07-14 Last updated: 2020-06-27

Tags: c#, xml, formatting

I have an XML string as such:

<?xml version='1.0'?><response><error code='1'> Success</error></response>

There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:

<?xml version='1.0'?>
<error code='1'> Success</error>

Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand?

#84 Best answer 1 of Format XML string to print friendly XML string (Score: 333)

Created: 2009-07-14 Last updated: 2018-04-21

You will have to parse the content somehow … I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here’s a working example using LINQ to format an input XML string.

string FormatXml(string xml)
         XDocument doc = XDocument.Parse(xml);
         return doc.ToString();
     catch (Exception)
         // Handle and throw if fatal exception here; don't just ignore them
         return xml;

[using statements are ommitted for brevity]

#84 Best answer 2 of Format XML string to print friendly XML string(Score: 196)

Created: 2009-07-14 Last updated: 2020-01-28

Use XmlTextWriter

public static string PrintXML(string xml)
	string result = "";

	MemoryStream mStream = new MemoryStream();
	XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
	XmlDocument document = new XmlDocument();

        // Load the XmlDocument with the XML.

        writer.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter

        // Have to rewind the MemoryStream in order to read
        // its contents.
        mStream.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader sReader = new StreamReader(mStream);

        // Extract the text from the StreamReader.
        string formattedXml = sReader.ReadToEnd();

        result = formattedXml;
	catch (XmlException)
        // Handle the exception


	return result;

See also original question in stackoverflow

#85: How to put space character into a string name in XML? (Score: 193)

Created: 2012-06-02 Last updated: 2012-06-02

Tags: android, xml, whitespace

i have defined some strings in the strings.xml file. Now I need to put some extra space between some numbers in the string. When I type extra space characters this is not showing on the application though.


<string name="spelatonertext3">-4, 5, -5, 6, -6,

And if I put extra space like this:

<string name="spelatonertext3">-4,  5, -5,   6,  -6,

It just looks the same on the app. How can I make space characters into the XML string?

#85 Best answer 1 of How to put space character into a string name in XML? (Score: 442)

Created: 2012-06-02 Last updated: 2013-10-24

to use white space in xml as string use &#160;. XML won’t take white space as it is. it will trim the white space before setting it. So use &#160; instead of single white space

#85 Best answer 2 of How to put space character into a string name in XML?(Score: 67)

Created: 2012-06-02 Last updated: 2012-06-02

Insert \u0020 directly in the XML for a blank you would like to preserve.

<string name="spelatonertext3">-4, \u00205, \u0020\u0020-5, \u00206, \u0020-6,</string>

See also original question in stackoverflow

#86: Error: The processing instruction target matching "[xX][mM][lL]" is not allowed (Score: 193)

Created: 2013-11-10 Last updated: 2020-04-10

Tags: java, xml, xslt

This error,

The processing instruction target matching “[xX][mM][lL]” is not allowed

occurs whenever I run an XSLT page that begins as follows:

<?xml version="1.0" encoding="windows-1256"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="">
  <xsl:include href="../header.xsl"/>
  <xsl:template match="/">
    <xsl:call-template name="pstyle"/>
    <xsl:call-template name="Validation"/>
    <xsl:variable name="strLang">
      <xsl:value-of select="//lang"/>
    <!-- ////////////// Page Title ///////////// -->
        <xsl:value-of select="//ListStudentFinishedExam.Title"/>

Note: I removed any leading spaces before the first line, but the error still occurs!

#86 Best answer 1 of Error: The processing instruction target matching "[xX][mM][lL]" is not allowed (Score: 393)

Created: 2013-11-11 Last updated: 2014-06-21

Xerces-based tools will emit the following error

The processing instruction target matching "[xX][mM][lL]" is not allowed.

when an XML declaration is encountered anywhere other than at the top of an XML file.

This is a valid diagnostic message; other XML parsers should issue a similar error message in this situation.

To correct the problem, check the following possibilities:

  1. Some blank space or other visible content exists before the <?xml ?> declaration.

Resolution: remove blank space or any other visible content before the XML declaration.

  1. Some invisible content exists before the <?xml ?> declaration. Most commonly this is a Byte Order Mark (BOM).

Resolution: Remove the BOM using techniques such as those suggested by the W3C page on the BOM in HTML.

  1. A stray <?xml ?> declaration exists within the XML content. This can happen when XML files are combined programmatically or via cut-and-paste. There can only be one <?xml ?> declaration in an XML file, and it can only be at the top.

Resolution: Search for <?xml in a case-insensitive manner, and remove all but the top XML declaration from the file.

#86 Best answer 2 of Error: The processing instruction target matching "[xX][mM][lL]" is not allowed(Score: 21)

Created: 2018-06-03

Reason for me is 2 of following code in one xml

<?xml version="1.0" encoding="utf-8"?>

See also original question in stackoverflow

#87: Convert XML String to Object (Score: 192)

Created: 2010-07-06 Last updated: 2014-09-10

Tags: c#, xml, xml-parsing, xml-serialization

I am receiving XML strings over a socket, and would like to convert these to C# objects.

The messages are of the form:


I am new to .Net, and am not sure the best practice for performing this. I’ve used JAXB for Java before, and wasn’t sure if there is something similar, or if this would be handled a different way.

#87 Best answer 1 of Convert XML String to Object (Score: 285)

Created: 2010-07-06 Last updated: 2016-01-24

You need to use the xsd.exe tool which gets installed with the Windows SDK into a directory something similar to:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

And on 64-bit computers:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin

And on Windows 10 computers:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

On the first run, you use xsd.exe and you convert your sample XML into a XSD file (XML schema file):

xsd yourfile.xml

This gives you yourfile.xsd, which in a second step, you can convert again using xsd.exe into a C# class:

xsd yourfile.xsd /c

This should give you a file yourfile.cs which will contain a C# class that you can use to deserialize the XML file you’re getting - something like:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));

Should work pretty well for most cases.

Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (msg)serializer.Deserialize(memStream);

or use a StringReader:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (msg)serializer.Deserialize(rdr);

#87 Best answer 2 of Convert XML String to Object(Score: 242)

Created: 2013-10-27 Last updated: 2019-10-24

You have two possibilities.

Method 1. XSD tool

Suppose that you have your XML file in this location `C:\path\to\xml\file.xml`
  1. Open Developer Command Prompt
    You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
  2. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  3. Create XSD file from your xml file by typing xsd file.xml
  4. Create C# classes by typing xsd /c file.xsd

And that’s it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

Method 2 - Paste special

Required Visual Studio 2012+ with .Net Framework >= 4.5 as project target and 'Windows Communication Foundation' individual component installed
  1. Copy content of your XML file to clipboard
  2. Add to your solution new, empty class file (Shift+Alt+C)
  3. Open that file and in menu click Edit > Paste special > Paste XML As Classes
    enter image description here

And that’s it!


Usage is very simple with this helper class:

using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;

namespace Helpers
    internal static class ParseHelpers
        private static JavaScriptSerializer json;
        private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }

        public static Stream ToStream(this string @this)
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            stream.Position = 0;
            return stream;

        public static T ParseXML<T>(this string @this) where T : class
            var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;

        public static T ParseJSON<T>(this string @this) where T : class
            return JSON.Deserialize<T>(@this.Trim());

All you have to do now, is:

    public class JSONRoot
        public catalog catalog { get; set; }
    // ...

    string xml = File.ReadAllText(@"D:\file.xml");
    var catalog1 = xml.ParseXML<catalog>();
    string json = File.ReadAllText(@"D:\file.json");
    var catalog2 = json.ParseJSON<JSONRoot>();

See also original question in stackoverflow

#88: XPath: Get parent node from child node (Score: 192)

Created: 2015-01-30 Last updated: 2020-05-17

Tags: xml, xpath

I need get the parent node for child node title 50

At the moment I am using only


How could I get its parent? Result should be the store node.

<?xml version="1.0" encoding="utf-8"?>
<d:data xmlns:d="defiant-namespace" d:mi="23">
    <store d:mi="22">
        <book price="12.99" d:price="Number" d:mi="4">
            <title d:constr="String" d:mi="1">Sword of Honour</title>
            <category d:constr="String" d:mi="2">fiction</category>
            <author d:constr="String" d:mi="3">Evelyn Waugh</author>
        <book price="8.99" d:price="Number" d:mi="9">
            <title d:constr="String" d:mi="5">Moby Dick</title>
            <category d:constr="String" d:mi="6">fiction</category>
            <author d:constr="String" d:mi="7">Herman Melville</author>
            <isbn d:constr="String" d:mi="8">0-553-21311-3</isbn>
        <book price="8.95" d:price="Number" d:mi="13">
            <title d:constr="String" d:mi="10">50</title>
            <category d:constr="String" d:mi="11">reference</category>
            <author d:constr="String" d:mi="12">Nigel Rees</author>
        <book price="22.99" d:price="Number" d:mi="18">
            <title d:constr="String" d:mi="14">The Lord of the Rings</title>
            <category d:constr="String" d:mi="15">fiction</category>
            <author d:constr="String" d:mi="16">J. R. R. Tolkien</author>
            <isbn d:constr="String" d:mi="17">0-395-19395-8</isbn>
        <bicycle price="19.95" d:price="Number" d:mi="21">
            <brand d:constr="String" d:mi="19">Cannondale</brand>
            <color d:constr="String" d:mi="20">red</color>

#88 Best answer 1 of XPath: Get parent node from child node (Score: 352)

Created: 2015-01-30 Last updated: 2019-07-28

Use the parent axes with the parent node’s name.


This XPath will only select the parent node if it is a store.

But you can also use one of these


These xpaths will select any parent node. So if the document changes you will always select a node, even if it is not the node you expect.


What happens in the given example where the parent is a bicycle but the parent of the parent is a store?

Does it ascent?

No, it only selects the store if it is a parent of the node that matches //*[title="50"].

If not, is there a method to ascent in such cases and return None if there is no such parent?

Yes, you can use ancestor axes


This will select all ancestors of the node matching //*[title="50"] that are ` stores. E.g.

<data xmlns:d="defiant-namespace" d:mi="23">
	<store mi="1">
        <store mi="22">
            <book price="8.95" d:price="Number" d:mi="13">
                <title d:constr="String" d:mi="10">50</title>
                <category d:constr="String" d:mi="11">reference</category>
                <author d:constr="String" d:mi="12">Nigel Rees</author>

XPath selection result

#88 Best answer 2 of XPath: Get parent node from child node(Score: 35)

Created: 2017-03-15 Last updated: 2017-04-13

Just as an alternative, you can use ancestor.


It’s more powerful than parent since it can get even the grandparent or great great grandparent

See also original question in stackoverflow

#89: What is the difference between Linq to XML Descendants and Elements (Score: 190)

Created: 2010-09-13 Last updated: 2011-10-07

Tags: c#, .net, xml, linq-to-xml

I have came across both these keywords in the VS IntelliSense. I tried to googling the difference between them and did not get a clear answer. Which one of these have the best performance with small to medium XML files. Thanks

#89 Best answer 1 of What is the difference between Linq to XML Descendants and Elements (Score: 304)

Created: 2010-09-13 Last updated: 2010-09-13

Elements finds only those elements that are direct descendents, i.e. immediate children.

Descendants finds children at any level, i.e. children, grand-children, etc…

Here is an example demonstrating the difference:

<?xml version="1.0" encoding="utf-8" ?>
    <bar>Test 1</bar>
        <bar>Test 2</bar>
    <bar>Test 3</bar>


XDocument doc = XDocument.Load("input.xml");
XElement root = doc.Root;

foreach (XElement e in root.Elements("bar"))
    Console.WriteLine("Elements : " + e.Value);

foreach (XElement e in root.Descendants("bar"))
    Console.WriteLine("Descendants : " + e.Value);


Elements : Test 1
Elements : Test 3
Descendants : Test 1
Descendants : Test 2
Descendants : Test 3

If you know that the elements you want are immediate children then you will get better performance if you use Elements instead of Descendants.

#89 Best answer 2 of What is the difference between Linq to XML Descendants and Elements(Score: 21)

Created: 2010-09-13

Descendants will search the entire subtree of the current element for the specified name (or will return a flattened version of the tree if no name is provided), whereas Elements searches only the immediate children of the current element.

See also original question in stackoverflow

#90: How to set RecyclerView app:layoutManager="" from XML? (Score: 189)

Created: 2016-02-28 Last updated: 2019-08-19

Tags: android, xml, android-recyclerview, androidx

How to set RecyclerView layoutManager from XML?


#90 Best answer 1 of How to set RecyclerView app:layoutManager="" from XML? (Score: 308)

Created: 2016-02-28 Last updated: 2020-06-20

As you can check in the doc:

Class name of the Layout Manager to be used.

The class must extend androidx.recyclerview.widget.RecyclerViewView$LayoutManager and have either a default constructor or constructor with the signature (android.content.Context, android.util.AttributeSet, int, int)

If the name starts with a '.', application package is prefixed. Else, if the name contains a '.', the classname is assumed to be a full class name. Else, the recycler view package (androidx.appcompat.widget) is prefixed

With androidx you can use:


With the support libraries you can use:

    app:layoutManager="" >

Also you can add these attributes:

  • android:orientation = "horizontal|vertical": to control the orientation of the LayoutManager (eg:LinearLayoutManager)
  • app:spanCount: to set the number of columns for GridLayoutManager





You can also add them using the tools namespace (i.e. tools:orientation and tools:layoutManager) and then it only impacts the IDE preview and you can continue setting those values in code.

#90 Best answer 2 of How to set RecyclerView app:layoutManager="" from XML?(Score: 89)

Created: 2017-02-23

if you want use it with LinearLayoutManager

    app:layoutManager="" >

that equivalent to

LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());

See also original question in stackoverflow

  1. This page use API to get the relevant data from stackoverflow community.
  2. Content license on this page is CC BY-SA 3.0.
  3. score = up votes - down votes.