0

I am writing xml with c#, here is the xml,

<?xml version="1.0" encoding="utf-16"?>
<game xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</game>

my code goes here:

XmlDocument doc = new XmlDocument();
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "UTF-16", null);
doc.AppendChild(decl);
XmlElement game = doc.CreateElement("game");  
doc.AppendChild(game);
XmlNode xmldocSelect = doc.SelectSingleNode("game");
//Crteate Attribute
XmlAttribute xmln = doc.CreateAttribute("xmln");
xmln.Value =":xsi="http://www.w3.org/2001/XMLSchema-instance"";
XmlAttribute xmlns = doc.CreateAttribute("xmlns");
xmlns.Value =":xsd="http://www.w3.org/2001/XMLSchema"";
xmldocSelect.Attributes.Append(xmln);
xmldocSelect.Attributes.Append(xmlns);

but because the attributes has http, it doesn't work...anyone know how to write those attributes? Thanks...

3
  • You are creating the attributes wrong. The name of the attribute is not xmln, that is the namespace. The name is xsi and value is http://.... Commented May 11, 2015 at 8:44
  • Any error that you are receiving here ? Commented May 11, 2015 at 8:51
  • : Unexpected symbol `http' Commented May 11, 2015 at 8:54

1 Answer 1

1

The attribute names are xsd and xsi - xmlns is a namespace prefix that's built into the spec.

You'd create like this:

var doc = new XmlDocument();

var declaration = doc.CreateXmlDeclaration("1.0", "UTF-16", null);
doc.AppendChild(declaration);

var game = doc.CreateElement("game");            
game.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
game.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
doc.AppendChild(game);

Unless you have good reason to stick with the old XmlDocument API, I'd be using LINQ to XML:

var doc = new XDocument(
    new XDeclaration("1.0", "UTF-16", null),
    new XElement("game",
        new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
        new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema")));
Sign up to request clarification or add additional context in comments.

Comments

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.