用XPath解析XML数据

本文关键字:数据 XML 解析 XPath | 更新日期: 2023-09-27 18:12:59

我有一个像这样的XML文件:

<Adresses> 
    <Address1>
      <XPath>//Address/Local[001]/AddressLine1</XPath>
      <Key>1</Key>
    </Address1>
    <Address2>
      <XPath>//Address/Local[002]/AddressLine1</XPath>
      <Key>2</Key>
    </Address2>
    <Address3>
      <XPath>//Address/Local[003]/AddressLine1</XPath>
      <Key>3</Key>
    </Address3>
    <Address4>
      <XPath>//Address/Local[004]/AddressLine1</XPath>
      <Key>4</Key>
    </Address4>
    <Address5>
      <XPath>//Address/Local[005]/AddressLine1</XPath>
      <Key>5</Key>
    </Address5>
</Adresses> 

我想在c#中使用XPath来解析XML值。在本例中,我想将元素<XPath>上的Local[002],Local[003], Local[004]和Local[005]替换为Local[001]。

用XPath解析XML数据

您可以使用LINQ to XML轻松地完成此操作。

这里有一个我拼凑起来的非常简单的例子:

var xml = @"<Adresses> 
    <Address1>
      <XPath>//Address/Local[00X]/AddressLine1</XPath>
      <Key>1</Key>
    </Address1>
    <Address2>
      <XPath>//Address/Local[00X]/AddressLine2</XPath>
      <Key>2</Key>
    </Address2>
    <Address3>
      <XPath>//Address/Local[00X]/AddressLine3</XPath>
      <Key>3</Key>
    </Address3>
    <Address4>
      <XPath>//Address/Local[00X]/AddressLine4</XPath>
      <Key>4</Key>
    </Address4>
    <Address5>
      <XPath>//Address/Local[00X]/AddressLine5</XPath>
      <Key>5</Key>
    </Address5>
</Adresses> ";
Console.WriteLine(xml);
var xDoc = XDocument.Parse(xml);
foreach(var elem in xDoc.Descendants("XPath")){
  var key = Convert.ToInt32((elem.NextNode as XElement).Value);
  elem.Value = string.Format("//Address/Local[{0}]/AddressLine{1}",key.ToString("000"),key);
}
Console.WriteLine(xDoc.ToString());

您的要求不是很清楚。当然,XPATH只能带您到此为止,因为它仅用于在XML文档中导航。你可以用它来帮助你找到你想要的元素,但你需要其他的东西来做实际的替换。

使用LINQ to XML(结合正则表达式):

var doc = XDocument.Load(@"C:'path'to'file.xml");
var xpath = "/Adresses/*/XPath";
var query = doc.XPathSelectElements(xpath);
foreach (var element in query)
{
    var newValue = Regex.Replace(element.Value, @"Local'['d{3}']", "Local[001]");
    element.Value = newValue;
}

使用XSLT可能是一种选择,但我不确定在这种情况下如何使用它。但是我打赌它不会很漂亮(与上面的代码相比)。