0

I am having a horrible time trying to get this to work. I have an existing XML file, and I simply need to add xmlns="http://url.com/path_v1_0" to an existing tag (the url.com is arbitrary, I have something else I need to put in there instead). This needs to be in C#. The rest of the file needs to stay exactly as it is, just the xmlns piece needs to be added.

Here is a snippet of what I have:

<?xml version="1.0" encoding="utf-8"?>
<content>
  <block id="root">
    <identification>

here is a snippet of what I need:

<?xml version="1.0" encoding="utf-8"?>
<content xmlns="http://url.com/path_v1_0">
  <block id="root">
    <identification>
4
  • Does this have to work for arbitrary input or do you have a fixed set of known files that you want to convert? Commented Apr 30, 2012 at 15:01
  • This is needed to add to any file in an arbitrary list, all of the files will have the same format and the same <content> tag. Commented Apr 30, 2012 at 15:06
  • How do you produce the XML today? See for example stackoverflow.com/questions/443250/… Commented Apr 30, 2012 at 15:06
  • It's produced programmatically in a batch process but without the xmlns tag. Commented Apr 30, 2012 at 15:12

4 Answers 4

1

Since you're dealing with XML generated by a tool that will always output the XML in a certain format, you can probably get away with simply performing some string manipulation:

var prefix = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<content>";

var xml = File.ReadAllText(pathToXmlFile);

if (!xml.StartsWith(prefix))
{
    throw new Exception("Wrong format");
}

xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
      "<content xmlns=\"http://url.com/path_v1_0\">" +
      xml.Substring(prefix.Length);

File.WriteAllText(pathToXmlFile, xml);
Sign up to request clarification or add additional context in comments.

Comments

1

Ok at the risk of having the XML zealots jumping all over my head, the simplest way of doing this is as follows:

  TextReader myInputFile = new StreamReader("test.xml");
  TextWriter myOutputFile = new StreamWriter("newtest.xml");

  myOutputFile.WriteLine(myInputFile.ReadLine());
  myOutputFile.WriteLine("<content xmlns=\"http://url.com/path_v1_0\">");

  string line = myInputFile.ReadLine(); // Waste the original <content> line

  while ((line = myInputFile.ReadLine()) != null)
  {
    myOutputFile.WriteLine(line);
  }

  myInputFile.Close();
  myOutputFile.Close();

Now as I say, this is absolutely NOT the correct XML standards way to do it, there are a few potential problems, least of which is your highly likely not to be adding a UTF-8 formatted string when you add the new line in.

It is however, probably the fastest and simplest to understand without getting tied up in all the various different XML API's that .NET now offers.

If you want to got the "correct" way then you need to be looking at the documentation for XDocument & XElement , using a bit of Linq to XML and the various methods in these classes you can very easily add the XMLNS tag into a given element followed by saving the XML.

Comments

0

Use this routine to set the namespace to your xml

    public static void SetDefaultXmlNamespace(XElement element, XNamespace xmlns)
    {
        if (element.Name.NamespaceName == string.Empty)
            element.Name = xmlns + element.Name.LocalName;

        foreach (var e in element.Elements())
            SetDefaultXmlNamespace(element, xmlns);
    }

Call it as below

XDocument doc = XDocument.Load(xmlfilepath);
SetDefaultXmlNamespace(doc.Root, "http://url.com/path_v1_0");

Comments

0

If you are willing to try Linq2XML heres a little example:

XDocument doc = XDocument.Load("path/to/file.xml");
doc.Root.Attribute("xmlns").Value = "http://url.com/path_v1_0";

You'll need a

using System.Xml.Linq;

//EDIT: I've tried it with an existing XML file which already has a xmlns attribute. So dtb is right. Here's a working example:

XDocument oldDoc = XDocument.Load(@"c:\logs\asd.xml");
XNamespace ns = "http://url.com/path_v1_0";
XElement newRoot = new XElement(ns + oldDoc.Root.Name.LocalName, oldDoc.Root.Descendants());
XDocument newDoc = new XDocument(newRoot);

3 Comments

This does not work. doc.Root.Attribute("xmlns") returns null. If you change it to doc.Root.Add(new XAttribute("xmlns", "http://...")); it throws an exception: "The prefix '' cannot be redefined from '' to 'http://...' within the same start element tag."
This doesn't work as well. If you don't recursively add the namespace to all elements in the document, you end up with <content xmlns="http://..."><foo xmlns="">....
Another fact i didn't notice. Thank you. I've never ran into exactly this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.