2014-12-07 28 views
-1

我想在這樣格式的XML:如何在C#中使用WriteStartDocument WriteStartElement WriteAttributeString格式化XML?

<?xml version="1.0" encoding="UTF-8"?> 
<ftc:A xmlns="urn:oecd:ties:stfatypes:v1" xmlns:ftc="urn:oecd:ties:a:v1" xmlns:xsi="http://www.a.com/2001/XMLSchema-instance" version="1.1" xsi:schemaLocation="urn:oecd:ties:a:v1 aXML_v1.1.xsd"> 
    <ftc:b> 
     <z issuedBy = "s">1</z> 
     <x>CO</x> 
    </ftc:b> 
</ftc:A> 

我忘記了屬性issuedBy, 我有麻煩寫的屬性白衣方法:

writer.WriteStartDocument(); 
writer.WriteStartElement(); 
writer.WriteAttributeString(); 
writer.WriteElementString(); 

我只需要在C#中的例子請:) :)

+0

對於這個,使用'XDocument'(LINQ to XML)不是更容易嗎? – t3chb0t 2014-12-07 20:41:28

回答

1

就像t3chb0t所說,像XDocument這樣的較新的類將使這更容易。但假設你需要使用XmlWriter,你可以這樣做:

const string rootNamespace = "urn:oecd:ties:stfatypes:v1"; 
const string ftcNamespace = "urn:oecd:ties:a:v1"; 
const string xsiNamespace = "http://www.a.com/2001/XMLSchema-instance"; 

var settings = new XmlWriterSettings 
{ 
    Indent = true, 
}; 

var sb = new StringBuilder(); 
using (var writer = XmlWriter.Create(sb, settings)) 
{ 
    writer.WriteStartDocument(); 
    writer.WriteStartElement("ftc", "A", ftcNamespace); 
    writer.WriteAttributeString("xmlns", "", null, rootNamespace); 
    writer.WriteAttributeString("xmlns", "ftc", null, ftcNamespace); 
    writer.WriteAttributeString("xmlns", "xsi", null, xsiNamespace); 
    writer.WriteAttributeString("version", "1.1"); 
    writer.WriteAttributeString("schemaLocation", xsiNamespace, "urn:oecd:ties:a:v1 aXML_v1.1.xsd"); 
    writer.WriteStartElement("b", ftcNamespace); 
    writer.WriteElementString("z", rootNamespace, "1"); 
    writer.WriteElementString("x", rootNamespace, "CO"); 
    writer.WriteEndElement(); 
    writer.WriteEndElement(); 
    writer.WriteEndDocument(); 
} 
+1

你有沒有試過這段代碼?你應該使用['WriteStartElement(「ftc」,「A」,「ftcNamespace」)'](http://msdn.microsoft.com/en-us/library/7cdfkth5.aspx) – 2014-12-07 21:53:38

+0

你有什麼是正確的方法做到這一點。我以爲我曾嘗試過,但是看到XmlWriter在下一行拋出一個異常,我將默認名稱空間設置爲rootNamespace。所以我讓它與「ftc:A」破解工作,這是不正確的,但工作。回想起來,我可能不小心錯過了顯式前綴的傳遞。我將編輯答案來反映這一點。謝謝! – daspek 2014-12-07 22:26:31

+0

反應非常好,並作品daspek,如果你說這是XDocument更容易,就像我看到它,非常感謝你 – 2014-12-08 01:32:15