2009-08-27 21 views
19

これは初心者のxml質問かもしれませんが、次のようなXML文書をどのように生成できますか?名前空間と接頭辞を持つxmlをXElementで記述するにはどうすればよいですか?

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

これを書いてもらえれば、残りの問題を解決することができます。

理想的には、LINQ to XML(XElement、XNamespaceなど)をC#で使用したいのですが、これがXmlDocumentsとXmlElementsでより簡単に/よりうまく実行できる場合、

ありがとうございました!

答えて

39

が希望の出力を作成する小さな例です。

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

あなたがそこにコロンを必要としないのですか?また、 'XNamespace.Xmlns'は' http:// www.w3.org/2000/xmlns/'を出力しませんか? –

+0

@ BrainStorm.exeいいえ、もともと回答したとおり、コードは期待通りに機能します。文字列にXNamespaceが追加されると、コロンが自動的に追加されます。これは手動で実行する必要はありません。 – techvice

+0

ここに[XNamespaceと文字列の加算演算子を記述したドキュメント](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それは似ていますXmlDocumentオブジェクトのための出力

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

必要がありますされています

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

は、このコードを試してみてください。それが動作するために

string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName); 
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);` 
関連する問題