2013-07-02 25 views
6

tôi cần để có thể tạo ra một tài liệu XML trông như thế này:Làm cách nào để thêm thuộc tính xml với các tiền tố/không gian tên khác nhau trong C#?

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

Dưới đây là mã của tôi:

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

Thật không may, những gì tôi nhận được cho thuộc tính thứ hai với tiền tố thứ hai không có tiền tố nào cả. Nó chỉ là "attrTwo" - giống như thuộc tính schemaVersion.

Vì vậy, có cách nào để có các tiền tố khác nhau cho các thuộc tính trong phần tử gốc trong C# không?

Trả lời

2

Đây chỉ là hướng dẫn cho bạn. Có thể là bạn có thể làm:

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

này sẽ cho kết quả:

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

Hy vọng điều này sẽ giúp đỡ bất kỳ!

+0

đáng lưu ý rằng NameTable và AddNameSpace chỉ cần thiết nếu bạn cần xác định tốc độ của không gian tên thay vì quy ước đặt tên mặc định (d1p1, d1p2, ...) –

0

Tôi thấy a post on another question đã kết thúc giải quyết vấn đề. Về cơ bản tôi đã tạo một chuỗi có tất cả xml trong đó, sau đó sử dụng phương thức LoadXml trên một cá thể của XmlDocument.

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); 
Các vấn đề liên quan