2013-07-02 10 views
6

Şöyle bir XML belgesi oluşturmak gerekiyor: MaalesefC# 'da farklı önekler/ad alanları ile xml özniteliklerini nasıl ekleyebilirim?

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); 

, ikinci öneki ile ikinci özellik için ne çekiyor: Burada

<?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> 

kod bu hiçbir önek değildir. Bu sadece "attrTwo" - schemaVersion özniteliği gibi.

Yani, C# kök öğesindeki öznitelikler için farklı öneklere sahip olmanın bir yolu var mı?

cevap

2

Bu sadece sizin için bir kılavuzdur. Yapabileceğiniz olabilir:

 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"); 

Bu neden olacaktır:

 <?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" /> 

Umut bu herhangi bir yardım olacak!

+0

NameTable ve addNamespace Bunun yerine varsayılan adlandırma kuralını ad alanının steno belirlemek gerekir yalnızca gerekli olduğunu belirtmek gerekir (d1p1, d1p2, ...) –

0

Sorunu çözen a post on another question'u gördüm. Temel olarak sadece içindeki tüm xml'leri içeren bir dize yarattım, daha sonra bir XmlDocument örneğinde LoadXml yöntemini kullandım.

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); 
İlgili konular