2

XDocument に新しい XLink ノードをプログラムで追加しようとしていますが、.Net は原子化された名前空間と名前としてそれらを作成しているようで、XLink ノードを XML に追加するコードが見つかりませんか?

私のコードは次のようになります。

//read in the current XML content
XDocument content = XDocument.Parse(xmlContent);

//add a new node called large images
XElement newNode = new XElement("large_images", "");
newNode.SetAttributeValue("{xmlns}xlink", "http://www.w3.org/1999/xlink");
newNode.SetAttributeValue("{xlink}type", "simple");
newNode.SetAttributeValue("{xlink}href", "tcm:5-550");
newNode.SetAttributeValue("{xlink}title", "of1_454x340.jpg");
content.Add(newNode);

残念ながら、この newNode は次のようになります。

<large_images p1:xlink="http://www.w3.org/1999/xlink" p2:type="simple" p2:href="tcm:5-550" p2:title="of1_454x340.jpg" xmlns:p2="xlink" xmlns:p1="xmlns"></large_images>

しかし、ノードが XML 検証に合格するには、ノードが次のようになっている必要があります。

<large_images xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="tcm:5-550" xlink:title="of1_454x340.jpg"></large_images>

誰でも助けることができますか?これは別の方法で可能に違いないように思われるので、String.Replace() ルートをたどりたくありませんか?

ありがとう

ライアン

4

1 に答える 1

6

私はそれを次のようにします:

XNamespace ns = "http://www.w3.org/1999/xlink";

XElement newNode = new XElement("large_images",
    new XAttribute(XNamespace.Xmlns + "xlink", ns),
    new XAttribute(ns + "type", "simple),
    new XAttribute(ns + "href", "tcm:5-550"),
    new XAttribute(ns + "title", "of1_454x340.jpg"));

これにより、次の XML が生成されます。

<large_images xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
    xlink:href="tcm:5-550" xlink:title="of1_454x340.jpg" />
于 2011-02-12T11:58:55.173 に答える