10

値を持つファセットを持つアイテムを選択するために XPath を使用しようとしていますLocationが、現在、すべてのアイテムを選択しようとしても失敗します。foreachループ) 。元のクエリを作成するか、XPath をまったく機能させることができれば幸いです。

XML

<?xml version="1.0" encoding="UTF-8" ?>
<Collection Name="My Collection" SchemaVersion="1.0" xmlns="http://schemas.microsoft.com/collection/metadata/2009" xmlns:p="http://schemas.microsoft.com/livelabs/pivot/collection/2009" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FacetCategories>
    <FacetCategory Name="Current Address" Type="Location"/>
    <FacetCategory Name="Previous Addresses" Type="Location" />
</FacetCategories>
    <Items>
        <Item Id="1" Name="John Doe">
            <Facets>
                <Facet Name="Current Address">
                    <Location Value="101 America Rd, A Dorm Rm 000, Chapel Hill, NC 27514" />
                </Facet>
                <Facet Name="Previous Addresses">
                    <Location Value="123 Anywhere Ln, Darien, CT 06820" />
                    <Location Value="000 Foobar Rd, Cary, NC 27519" />
                </Facet>
            </Facets>
        </Item>
    </Items>
</Collection>

C#

public void countItems(string fileName)
{
    XmlDocument document = new XmlDocument();
    document.Load(fileName);
    XmlNode root = document.DocumentElement;
    XmlNodeList xnl = root.SelectNodes("//Item");
    Console.WriteLine(String.Format("Found {0} items" , xnl.Count));
}

メソッドにはこれ以外にもありますが、実行されるのはこれだけなので、問題はここにあると思います。root.ChildNodes正確に呼び出すFacetCategoriesと and が返ってくるItemsので、完全に途方に暮れています。

ご協力いただきありがとうございます!

4

2 に答える 2

27

ルート要素には名前空間があります。名前空間リゾルバーを追加し、クエリ内の要素にプレフィックスを付ける必要があります。

この記事では、その解決策について説明します。1 つの結果が得られるようにコードを修正しました。

public void countItems(string fileName)
{
    XmlDocument document = new XmlDocument();
    document.Load(fileName);
    XmlNode root = document.DocumentElement;

    // create ns manager
    XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(document.NameTable);
    xmlnsManager.AddNamespace("def", "http://schemas.microsoft.com/collection/metadata/2009");

    // use ns manager
    XmlNodeList xnl = root.SelectNodes("//def:Item", xmlnsManager);
    Response.Write(String.Format("Found {0} items" , xnl.Count));
}
于 2010-04-07T16:06:29.333 に答える
13

ルート ノードに XML 名前空間があるため、XML ドキュメントには "Item" などはなく、"[namespace]:Item" のみが存在するため、XPath でノードを検索する場合は、名前空間を指定する必要があります。

それが気に入らない場合は、local-name() 関数を使用して、ローカル名 (プレフィックス以外の名前部分) が探している値であるすべての要素に一致させることができます。少し醜い構文ですが、機能します。

XmlNodeList xnl = root.SelectNodes("//*[local-name()='Item']");
于 2010-04-07T16:33:58.190 に答える