簡體   English   中英

從XML文件獲取屬性

[英]Get attribute from XML file

我有一個具有以下結構的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<DocumentInterface transactionNo="0102014146" creationDate="2014-05-26" version="1.4" ilnSender="4306286000007" ilnRecipient="407731000008" creationTime="17:00:30" xsi:schemaLocation="http://xmlschema.metro-mgp.com/outdoc/DocumentInterface DocumentInterface.xsd" xmlns="http://xmlschema.metro-mgp.com/outdoc/DocumentInterface" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CheckSum>
    <DocCount>1</DocCount>
    <PayableAmount>682.38</PayableAmount>
</CheckSum>
 ......
    </DocumentInterface>

我需要修改屬性transactionNo。 從C#中,我嘗試使用以下代碼從文件中獲取值:

       XmlDocument doc = new XmlDocument();
        using (FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
        {

            doc.PreserveWhitespace = true;
            doc.Load(fs);
        }

        XmlAttribute formTransactionNo = (XmlAttribute)doc.SelectSingleNode("//DocumentInterface/@transactionNo");
        if (formTransactionNo != null)
        {
             prmNewValue=formTransactionNo.Value;
        }

但是formTransactionNo總是為null。你能幫我得到這個值嗎? 謝謝

您不能使用XPath選擇屬性。 實際上,您這里不需要XPath-它很容易從根元素獲取屬性:

XmlAttribute transactionNo = doc.DocumentElement.Attributes["transactionNo"];
string prmNewValue = transactionNo.Value;
// output: 0102014146

更新屬性值也很簡單:

transactionNo.Value = "007";
doc.Save(path_to_xml);

BTW考慮使用現代LINQ to XML方法來解析/更新xml。 例如,獲取此屬性值將如下所示:

var xdoc = XDocument.Load(newFileName);    
var prmNewValue = (string)xdoc.Root.Attribute("transactionNo");

或獲得應付金額

var ns = xdoc.Root.GetDefaultNamespace();
var payableAmount = 
    (decimal)xdoc.Root.Element(ns + "CheckSum").Element(ns + "PayableAmount");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM