我想使用正则表达式来查找16位数字的父节点并返回整个部分,但无法弄清楚如何操作,因此给出:
<Details>
<CreditCard cardnum="1234567890123456" ccv="123" exp="0212" cardType="1" name="joe" />
</Details>
我想退货:
<CreditCard cardnum="1234567890123456" ccv="123" exp="0212" cardType="1" name="joe" />
然后,我将使用解析xml并获取每个数字的属性并将其删除。
我尝试了
.*(\d{13,16}).*,但这会得到每个字符。
一次,我做:
XElement element = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length == 16)
.Count() == 1);
我无法弄清楚如何遍历elementsWithPossibleCCNumbers中的每个属性,例如:
foreach(var x in elementsWithPossibleCCNumbers)
{
//If attribute is number, replace value with empty string
}
注意:我现在删除了int.TryParse。
我决定这样做:
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length >= 13 && a.Value.Length <= 16)
.Count() == 1).Select(x=>x);
foreach(var x in elementsWithPossibleCCNumbers)
{
foreach(var a in x.Attributes())
{
xml = xml.Replace(a.Value, new String('*',12));
}
}
但是,如果第二个元素的属性为16位数字,则它仅替换部分属性值。
请您参考如下方法:
由于您的XML可能有很大的不同,因此我将执行以下操作。
假设XML像这样:
<Details>
<CreditCard cardnum="1234567890123456"
ccv="123"
exp="0212"
cardType="1"
name="joe" />
</Details>
不可知论的代码:
XElement element = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
int ccNumber;
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length == 16)
.Where(a => int.TryParse(a.Value, out ccNumber))
.FirstOrDefault() != null);
// Do not use ccNumber
// Use elementsWithPossibleCCNumbers
这可以扩展为包括许多属性...
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length == 16)
.Where(a => int.TryParse(a.Value, out ccNumber))
.FirstOrDefault() != null
&& d.Attributes().Count() == 5);
有许多可能性不包括使用Regex或对XML元素名称进行硬编码。我倾向于将Regex作为最后的手段,尤其是如果有更好的东西可以为我解析所有数据时。
更新1
elementsWithPossibleCCNumbers是包含1或MORE属性的XML元素,这些属性的长度为16位数字,是整数。在这种情况下,您无法确定,所以我将其更改为..
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length == 16)
.Where(a => int.TryParse(a.Value, out ccNumber))
.Count() == 1);
// Where only 1 attribute is 16 length and an int
再次扩展...
IEnumerable<XAttribute> attributesWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length == 16)
.Where(a => int.TryParse(a.Value, out ccNumber))
.Count() == 1)
.Select(e => e.Attributes()
.Where(a => a.Value.Length == 16)
.Where(a => int.TryParse(a.Value, out ccNumber))
.First());
