2009-08-27 22 views
19

Đây có thể là câu hỏi xml bắt đầu, nhưng làm cách nào tôi có thể tạo một tài liệu xml trông giống như sau?Làm thế nào tôi có thể viết xml với một không gian tên và tiền tố với XElement?

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com"> 
    <ci:field1>test</ci:field1> 
    <ca:field2>another test</ca:field2> 
</root> 

Nếu tôi có thể viết, tôi có thể giải quyết được vấn đề còn lại.

Lý tưởng nhất, tôi muốn sử dụng LINQ to XML (XElement, XNamespace, vv) với C#, nhưng nếu điều này có thể được thực hiện dễ dàng hơn/tốt hơn với XmlDocuments và XmlElements, tôi sẽ đi với điều đó.

Xin cảm ơn !!!

Trả lời

39

Dưới đây là một ví dụ nhỏ mà tạo ra sản lượng mà bạn muốn:

using System; 
using System.Xml.Linq; 

class Program 
{ 
    static void Main() 
    { 
     XNamespace ci = "http://somewhere.com"; 
     XNamespace ca = "http://somewhereelse.com"; 

     XElement element = new XElement("root", 
      new XAttribute(XNamespace.Xmlns + "ci", ci), 
      new XAttribute(XNamespace.Xmlns + "ca", ca), 
       new XElement(ci + "field1", "test"), 
       new XElement(ca + "field2", "another test")); 
    } 
} 
+0

Đừng bạn cần dấu hai chấm trong đó cho rằng để làm việc? Ngoài ra, không có đầu ra 'XNamespace.Xmlns'' http: // www.w3.org/2000/xmlns/'? –

+0

@ BrainStorm.exe No. Như đã trả lời ban đầu, mã hoạt động như mong đợi. Khi các XNamespace được thêm vào với chuỗi, dấu hai chấm được tự động thêm vào. Đây không phải là cái gì đó phải được thực hiện bằng tay. – techvice

+0

Đây là [tài liệu chi tiết toán tử bổ sung cho XNamespace và một chuỗi] (https://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.op_addition (v = vs.110). aspx) – techvice

-1
XNamespace ci = "http://somewhere.com"; 
XNamespace ca = "http://somewhereelse.com"; 
XElement root = new XElement(aw + "root", 
    new XAttribute(XNamespace.Xmlns + "ci", "http://somewhere.com"), 
    new XAttribute(XNamespace.Xmlns + "ca", "http://somewhereelse.com"), 
    new XElement(ci + "field1", "test"), 
    new XElement(ca + "field2", "another test") 
); 
Console.WriteLine(root); 

Th là nên đầu ra

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com"> 
    <ci:field1>test</ci:field1> 
    <ca:field2>another test</ca:field2> 
</root> 
-1

Đối XmlDocument nó tương tự như:

XmlAttribute attribute1 = sessionXml.CreateAttribute("s", "Attribute1", namespaceURI); 
XmlAttribute attribute2 = sessionXml.CreateAttribute("s", "Attribute2", namespaceURI); 
XmlAttribute attribute3 = sessionXml.CreateAttribute("s", "Attribute3", namespaceURI); 
XmlAttribute attribute4 = sessionXml.CreateAttribute("s", "Attribute4", namespaceURI); 
2

Hãy thử mã này:

string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName); 
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);` 
Các vấn đề liên quan