How to add xml attributes with different prefixes / namespaces in C #?

I need to create an XML document that looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <rootprefix:rootname noPrefix="attribute with no prefix" firstprefix:attrOne="first atrribute" secondprefix:attrTwo="second atrribute with different prefix"> ...other elements... </rootprefix:rootname> 

Here is my code:

 XmlDocument doc = new XmlDocument(); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); doc.AppendChild(declaration); XmlElement root = doc.CreateElement("rootprefix:rootname", nameSpaceURL); root.SetAttribute("schemaVersion", "1.0"); root.SetAttribute("firstprefix:attrOne", "first attribute"); root.SetAttribute("secondprefix:attrTwo", "second attribute with different prefix"); doc.AppendChild(root); 

Unfortunately, what I get for the second attribute with the second prefix is ​​not a prefix at all. It is simply "attrTwo" - as an attribute of schemaVersion.

So, is there a way to have different prefixes for the attributes in the root element in C #?

+6
source share
2 answers

This is just a guide for you. Perhaps you can:

  NameTable nt = new NameTable(); nt.Add("key"); XmlNamespaceManager ns = new XmlNamespaceManager(nt); ns.AddNamespace("firstprefix", "fp"); ns.AddNamespace("secondprefix", "sp"); root.SetAttribute("attrOne", ns.LookupPrefix("fp"), "first attribute"); root.SetAttribute("attrTwo", ns.LookupPrefix("sp"), "second attribute with different prefix"); 

This will lead to:

  <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <rootprefix:rootname schemaVersion="1.0" d1p1:attrOne="first attribute" d1p2:attrTwo="second attribute with different prefix" xmlns:d1p2="secondprefix" xmlns:d1p1="firstprefix" xmlns:rootprefix="ns" /> 

Hope this helps!

+2
source

I saw a post on another issue that ultimately solved the problem. I simply created a line that contained all of the xml, and then used the LoadXml method for the XmlDocument instance.

 string rootNodeXmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<rootprefix:rootname schemaVersion=\"1.0\" d1p1:attrOne=\"first attribute\"" + "d1p2:attrTwo=\"second attribute with different prefix\" xmlns:d1p2=\"secondprefix\"" + "xmlns:d1p1=\"firstprefix\" xmlns:rootprefix=\"ns\" />"; doc.LoadXml(rootNodeXmlString); 
0
source

Source: https://habr.com/ru/post/948557/


All Articles