按属性名称读取 XML 值

Posted

技术标签:

【中文标题】按属性名称读取 XML 值【英文标题】:Read XML Value By Attribute Name 【发布时间】:2018-12-05 12:46:35 【问题描述】:
<Customer>
    <Type H="General Information" ID="GeneralInfo">
         <Row>
             <C H="Customer Name">Mr. Robert</C>
             <C H="Relation">S/O. John</C>
             <C H="Date of Birth">01/01/1985</C>
        </Row>
    </Type>
    <Type H = "Other Details" ID = "ShareDet">
         <Row>
            <C H = "Address 1">XYZ</C>
            <C H = "Address 2">ABC</C>
        </Row>
    </Type>
</Customer>

我试图在 C# 中从上面的 XML 中读取“罗伯特先生”,但我做不到。 我试过下面的代码:

XmlDocument objXmlMain = new XmlDocument();
objXmlMain.LoadXml("Loading_Above_XMLSTRING");
string test = objXmlMain.SelectSingleNode("Customer/Type/Row/C/@H").Value;

我得到的结果是“客户名称”(即属性值)。 我想通过检查属性值“客户名称”来读取名称,我应该得到结果为“罗伯特先生

【问题讨论】:

XPath: How to select a node by its attribute?的可能重复 c# xpath by attribute name的任何互联网搜索结果 【参考方案1】:

你需要使用:

string test = objXmlMain.SelectSingleNode("Customer/Type/Row/C[@H='Customer Name']").Value;

Customer/Type/Row/C/@H xpath 查询选择 H 属性本身,.Value 返回该属性的文本。

【讨论】:

以上是关于按属性名称读取 XML 值的主要内容,如果未能解决你的问题,请参考以下文章