10

I have to create an XML document in C#.

The root element has to look like this:

<valuation-request 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:noNamespaceSchemaLocation="valuations.xsd">

I'm using the following

XmlElement root = X.CreateElement("valuation-request");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.SetAttribute("xsi:noNamespaceSchemaLocation", "valuations.xsd");

However this produces

<valuation-request 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     noNamespaceSchemaLocation="valuations.xsd"> //missing the xsi:

What am I missing?

3 Answers 3

8

Use the overload of SetAttribute, that takes namespace as well:

root.SetAttribute("noNamespaceSchemaLocation", 
    "http://www.w3.org/2001/XMLSchema-instance", 
    "valuations.xsd"
); 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm using root.SetAttribute("xsi:noNamespaceSchemaLocation", "valuations.xsd");. how would you suggest it should look?
try this root.SetAttribute("noNamespaceSchemaLocation", "valuations.xsd","w3.org/2001/XMLSchema-instance");
That returns <valuation-request xmlns:xsi="w3.org/2001/XMLSchema-instance" d1p1:noNamespaceSchemaLocation="w3.org/2001/XMLSchema-instance" xmlns:d1p1="valuations.xsd">
I swapped them round to look like root.SetAttribute("noNamespaceSchemaLocation", "w3.org/2001/XMLSchema-instance", "valuations.xsd"); ...bish bash bosh.. cheers
0

With writer you add it like this:

var writerSettings = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = " ",
            NewLineChars = Environment.NewLine,
            NewLineHandling = NewLineHandling.Replace,
            Encoding = new UTF8Encoding(false)
        };

XmlWriter writer = XmlWriter.Create("C:\test.xml", writerSettings);
writer.WriteStartDocument(false);
writer.WriteStartElement("valuation-request");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "http://www.gzs.si/e-poslovanje/sheme/eSLOG_1-5_EnostavniRacun.xsd");

Comments

0

Recently, I have encountered same issue. To resolve it, I've just add the follow line:

XmlAttribute noNamespaceSchemaLocationAttr = xmlDoc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");

1 Comment

that works just fine on my Code. Important to me was the XMLSchema-instance part

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.