如果您使用 .Net 訊息元件,則可以使用 XML 串行化屬性來標註程式代碼,當也伴隨著辨別欄位和/或屬性批註時,可能會導致相當複雜的 XPath 表達式。 這些複雜的 XPath 運算式可能是非標準表達式。 非標準 XPath 應僅用於直接繫結的協調流程,而且可能會因邏輯或實體繫結的協調流程而失敗。 直接系結協調流程不依賴管線來處理 XML 檔;因此,整個 XML 檔會在處理之前載入記憶體中。
標準和非標準 XPath
XPath 的標準形式或簡寫形式使用 XPath 規格中的縮寫語法http://www.w3.org/TR/xpath來指定位置路徑。 標準 XPath 表達式的一些區別屬性包括:
在默認情況下,
child::座標軸會應用於表達式的每個步驟。@是的簡短。attribute:://是的簡短。/descendant-or-self::node()/.是的簡短。self::node()..是的簡短。parent::node()標準 XPath 表示式是簡單的運算式,例如
/*[local-name()='element-name' and namespaceURI()='http://MyUri.org']/*[local-name()='element-name']/@*[local-name='attribute-name']。這可以與 XPath 的非標準形式形成對比。 此表單也稱為「一般表單」或「任意 XPath」,其特徵在於這些表達式可具有任意複雜性,且能結合多個軸:
//element-name//*[local-name()='element-name' and position()=2]。
範例
請考慮下列程式:
using System;
using System.IO;
using System.Xml.Serialization;
using Microsoft.XLANGs.BaseTypes;
namespace ComplexNetXPath
{
public class Animal
{
[Property( typeof(BTS.RetryCount) )]
public int NumberOfLegs;
}
public class Snake : Animal
{
public Snake()
{
NumberOfLegs = 0;
}
}
public class Dog : Animal
{
public Dog()
{
NumberOfLegs = 4;
}
}
public class Zoo
{
//
// Dogs and snakes are the possible animals of
// the week.
//
[XmlElement(typeof(Snake))]
[XmlElement(typeof(Dog))]
public Animal AnimalOfTheWeek;
}
class Class1
{
static void Main(string[] args)
{
XmlSerializer ser = new XmlSerializer(typeof(Zoo));
Stream s = Console.OpenStandardOutput();
Zoo z = new Zoo();
z.AnimalOfTheWeek = new Dog();
ser.Serialize( s, z );
s.Flush();
Console.WriteLine("------------------");
z.AnimalOfTheWeek = new Snake();
ser.Serialize( s, z );
s.Flush();
}
}
}
Zoo 類型中有一個動物欄位,其可以是蛇或狗。 Animal 實例中有一個名為 NumberOfLegs 的欄位,該欄位使用 PropertyAttribute 進行標註,並將 BTS.RetryCount 屬性分配給此欄位。
備註
實際的應用程式會定義自己的屬性。
當一周的動物是一隻狗時,串行化的 Zoo 實例看起來像這樣:
<Zoo>
<Dog>
<NumberOfLegs>4</NumberOfLegs>
</Dog>
</Zoo>
當一周的動物是蛇時,串行化的 Zoo 實例看起來像這樣:
<Zoo>
<Snake>
<NumberOfLegs>0</NumberOfLegs>
</Snake>
</Zoo>
考慮到與 .Net Zoo 類別相等的 XML 架構,選取 RetryCount 屬性的 XPath 運算式可讓蛇或狗的步驟出現在屬性的路徑上:
/*[local-name()='Zoo' and namespace-uri()='']/*[(local-name()='Dog' and namespace-uri()='') or (local-name()='Snake' and namespace-uri()='')]/*[local-name()='NumberOfLegs' and namespace-uri()='']
XML 管線元件無法處理這個非標準 XPath 運算式。 若要避免這種情況,多選 Xml 串行化屬性不應與 XML 管線搭配使用,在使用下列 xml 串行化屬性時應小心:
XmlElementAttribute
XmlAttributeAttribute
XmlArrayItemAttribute