1

my xml content in variable look like:

 var xml = DownloadString(@"http://192.168.1.50:8983/solr/core-live/select?q=*%3A*&wt=xslt&tr=custom.xsl");

DownloadString is a function/method

public static string DownloadString(string address) 
     {
        string text;
         using (var client = new WebClient()) 
         {
           text = client.DownloadString(address);
         }
           return text;
      }

and when i am debugging on xml variable and xml o/p look like:

<?xml version="1.0" encoding="UTF-8"?>
<xml version="1.0">
<item>
<sku>12944</sku>
<title>test</title</item>
</xml>

i want to remove second node(<xml version="1.0">) and last node(</xml>) from same variable.

then after save content in xml file using this:

 System.IO.File.WriteAllText("test.xml", xml);

regards, Jatin

Jatin Gadhiya
  • 1,955
  • 5
  • 23
  • 42

5 Answers5

8
XDocument xdoc = XDocument.Parse(xml);
xdoc.Declaration = null;
return xdoc;

C# creating XML output file without <?xml version="1.0" encoding="utf-8"?>

Community
  • 1
  • 1
user1040975
  • 420
  • 5
  • 16
1

Maybe you need to use replace method in string

                text = text.Replace("<xml version=\"1.0\">", "");
                text = text.Replace("</xml>", "");
ASalameh
  • 783
  • 1
  • 8
  • 29
0
    string filePath = "C:\\file.xml";
                List<string> strList = File.ReadAllLines(filePath).ToList();
                StringBuilder sb = new StringBuilder();
                int ctr = 0;
                foreach (string str in strList)
                {
                    ctr++;
                    if (ctr == 1 || ctr == strList.Count)
                        continue;
                    sb.Append(str);
                }
Thakur
  • 559
  • 6
  • 15
0

in my case in addition to @user1040975's solution to the problem I also had to set the XmlWriterSettings's OmitXmlDeclaration attribute as true, so the new declaration without the Encoding I created would appear, at the end the code looked like this:

XmlWriterSettings settings = new XmlWriterSettings()
{
    Encoding = new UTF8Encoding(false),
    OmitXmlDeclaration = true
};
using (XmlWriter xmlWriter = XmlWriter.Create(convertedPath, settings))
{
    XDocument xDoc = XDocument.Parse(innerXml);
    xDoc.Declaration = new XDeclaration("1.0",null,null);
    xDoc.Save(xmlWriter);
}
-1

I using both string replace() function on DownloadString() mathod.

I was try this code and its working fine.

public static string DownloadString(string address) 
        {
                    string text;
                    using (var client = new WebClient()) 
                    {
                        text = client.DownloadString(address);
                    }
                    return text.Replace("<xml version=\"1.0\">", "").Replace("</xml>", "");
        }
Jatin Gadhiya
  • 1,955
  • 5
  • 23
  • 42