我有一個使用一些資料創建的 XML 檔案,它始終以相同的方式創建,具有相同的資料量,如下例所示:
<cac:Party>
<cbc:EndpointID schemeID="Country">3023</cbc:EndpointID>
<cac:PartyIdentification>
<cbc:ID schemeID="Country">3023</cbc:ID>
</cac:PartyIdentification>
<cac:PartyName>
<cbc:Name>Test</cbc:Name>
</cac:PartyName>
<cac:PostalAddress>
<cbc:AddressFormatCode listAgencyID="###" listID="urn:oioubl:codelist:addressformatcode-1.1">StructuredLax</cbc:AddressFormatCode>
<cbc:StreetName>Test</cbc:StreetName>
<cbc:CityName>Test</cbc:CityName>
<cbc:PostalZone>Test</cbc:PostalZone>
<cac:Country>
<cbc:IdentificationCode>DK</cbc:IdentificationCode>
</cac:Country>
</cac:PostalAddress>
<cac:PartyTaxScheme>
<cbc:CompanyID schemeID="Country">3023</cbc:CompanyID>
<cac:TaxScheme>
<cbc:ID schemeID="urn:oioubl:id:taxschemeid-1.1" schemeAgencyID="320">63</cbc:ID>
<cbc:Name>Moms</cbc:Name>
</cac:TaxScheme>
</cac:PartyTaxScheme>
<cac:PartyLegalEntity>
<cbc:RegistrationName>Test/cbc:RegistrationName>
<cbc:CompanyID schemeID="Country">3023</cbc:CompanyID>
現在我想要編輯值:“3023”到“2020”(字串),但我只想為最后一個做。
到目前為止,我一直在嘗試使用“StreamReader StreamWriter Regex”,如下所示:
string docText = null;
using (StreamReader sr = new StreamReader(filename))
{
docText = sr.ReadToEnd();
}
Regex oldValue = new Regex("3023");
docText = oldValue.Replace(docText, "2020");
using (StreamWriter sw = new StreamWriter(filename))
{
sw.Write(docText);
}
我在這里遇到的一個明顯問題是它在整個檔案中一直在改變它,所以我的想法是可能使用子字串并找到最后一個“3023”的特定索引。所以因為檔案總是以相同的方式構建具有相同數量的值,所以我知道我想要的“3023”字串總是檔案中的第四個,所以我可以使用以下方法找到起始索引:
docText.IndexOf("3023", 4);
這給了我起始索引,我也知道數字序列是四個字母“3023”這將始終如此,因此我也可以找到結束索引。
不過,這是我停滯不前的地方,我不確定使用什么來替換使用索引的字串,可能還有更智能的方法,所以我很樂意接受任何指標。
謝謝。
uj5u.com熱心網友回復:
使用 Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication40
{
class Program
{
const string INPUT_FILENAME = @"c:\temp\test.xml";
const string OUTPUT_FILENAME = @"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(INPUT_FILENAME);
XElement CompanyID = doc.Descendants().Where(x => x.Name.LocalName == "CompanyID").Last();
CompanyID.Value = "2020";
doc.Save(OUTPUT_FILENAME);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521253.html
標籤:C#正则表达式xml代替
