【问题标题】:XPath query with multiple namespaces具有多个命名空间的 XPath 查询
【发布时间】:2019-09-13 15:41:14
【问题描述】:

你认为正确的 XPath 是在下面拉出都柏林核心标识符吗?

我添加了一个包含这些条目的命名空间管理器:

// Add the namespace.  
XmlNamespaceManager nsmgr = new XmlNamespaceManager(m_xml.NameTable);
nsmgr.AddNamespace("mets", "http://www.loc.gov/METS/");
nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
nsmgr.AddNamespace("dcterms", "http://purl.org/dc/terms/");

我已经尝试了 15 种左右不同的 XPath 迭代,包括以下迭代。当我没有收到错误时,结果为空。

//xml_uuid = m_xml.SelectSingleNode("/mets:mets/mets:dmdSec/mets:mdWrap/mets:xmlData/dcterms:dublincore/dc:identifier").Value;
xml_uuid = m_xml.SelectSingleNode("//dc:identifier",nsmgr).Value;

这是我正在使用的 xml:

<mets:mets xmlns:mets="http://www.loc.gov/METS/" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/version18/mets.xsd">
 <mets:metsHdr CREATEDATE="2017-03-08T20:13:27" />
 <mets:dmdSec ID="dmdSec_1">
   <mets:mdWrap MDTYPE="DC">
     <mets:xmlData>
       <dcterms:dublincore xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xsi:schemaLocation="http://purl.org/dc/terms/ http://dublincore.org/schemas/xmls/qdc/2008/02/11/dcterms.xsd">

         <dc:identifier>F2015.5</dc:identifier>

       </dcterms:dublincore>
     </mets:xmlData>
   </mets:mdWrap>
 </mets:dmdSec>
 etc...

我正在尝试将 dc:identifier - 在这种情况下为 F2015.5 - 分配给一个字符串。

【问题讨论】:

标签: c# xml xpath


【解决方案1】:

使用 xml linq 并忽略命名空间:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication131
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            string results = (string)doc.Descendants().Where(x => x.Name.LocalName == "identifier").FirstOrDefault();
        }
    }
}

【讨论】:

  • 我从 api 获取 xml,所以我必须这样做:XDocument.Parse(m_xml.OuterXml); 但您的方法在没有声明命名空间的情况下有效。发送。
  • 是的。有字符串时使用 Parse,读取文件或流时使用 Load。
【解决方案2】:

这是一个有效的答案。我相信主要是使用 .InnerText 而不是 .Value。

xml_uuid = m_xml.SelectSingleNode("//mets:xmlData[1]/dcterms:dublincore[1]/dc:identifier[1]", nsmgr).InnerText;

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多