假设我们有以下xml
文件
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book genre="novel" publicationdate="1997" ISBN="1-861001-57-8">
<title>Pride And Prejudice</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>24.95</price>
</book>
<book genre="textbook" publicationdate="2013" ISBN="1-861002-30-1">
<title>Head First C#</title>
<author>
<first-name>Jennifer</first-name>
<last-name>Greene</last-name>
</author>
<price>29.95</price>
</book>
</bookstore>
我想检查具有属性book
的元素genre="novel"
是否存在,如果不添加,请添加。
我已经编写了以下代码,它可以很好地工作。但是,如果有人编辑xml文件并意外地在单词“ novel”和双引号genre=" novel "
之间放置了额外的空格,或者说我是个白痴,并且在创建属性值时添加了额外的空格,则xpath会赢得不再有效,并且代码将在已有节点时添加一个节点。有没有办法使用SelectSingleNode
来忽略空格?
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Users\anonymous\Documents\file.xml");
string xpath = @"/bookstore/book [@genre='novel']";
var rootNode = doc.SelectSingleNode(@"/bookstore");
var bookNode = doc.SelectSingleNode(xpath);
if (bookNode == null)
{
XmlNode newNode = doc.CreateElement("book");
XmlAttribute genreAttribute = doc.CreateAttribute("genre");
genreAttribute.Value = @"novel";
newNode.Attributes.Append(genreAttribute);
rootNode.AppendChild(newNode);
}
doc.Save(@"C:\Users\anonymous\Documents\file.xml");
参考方案
使用normalize-space()
XPath函数:
string xpath = @"/bookstore/book [normalize-space(@genre)='novel']";
这将修剪所有前导或尾随的空白字符,但也将它们之间的任何空白字符序列标准化为一个空白。
注意:更精确地说,这仍然不能完全“忽略空白”。单例空格,如
<book genre="no vel"/>
将被保留并具有相关性。如果您想完全忽略空格,可以使用translate()
函数:
string xpath = @"/bookstore/book [translate(@genre,' ','')='novel']";
Div单击与单选按钮相同吗? - php有没有一种方法可以使div上的click事件与表单环境中的单选按钮相同?我只希望下面的div提交值,单选按钮很丑代码输出如下:<input id="radio-2011-06-08" value="2011-06-08" type="radio" name="radio_date…
故障排除“警告:session_start():无法发送会话高速缓存限制器-标头已发送” - php我收到警告:session_start()[function.session-start]:无法发送会话缓存限制器-标头已发送(错误输出开始如果我将表单数据提交到其他文件进行处理,则可以正常工作。但是,如果我将表单数据提交到同一页面,则会出现此错误。请建议<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0…
将python scikit学习模型导出到pmml - python我想将python scikit-learn模型导出到PMML。哪个python软件包最合适?我阅读了有关Augustus的内容,但是我无法使用scikit-learn模型找到任何示例。 python大神给出的解决方案 SkLearn2PMML是 JPMML-SkLearn命令行应用程序周围的薄包装。有关受支持的Scikit-Learn Estimator和…
如何使用PHP从动态输入字段捕获数组值? - javascript我正在编写一个在线时间跟踪网页,允许用户将学习时间输入该系统。用户将首先输入名称,然后根据日期输入学习时间。一天中可能会有多个学习时间。以下是我第一页的编码,<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"…
SOAPFaultException部署在Tomcat上时,但在GlassFish中工作正常 - java朋友们,我一直在尝试很多,阅读了很多论坛,但无法理解为什么出现此问题。我使用契约优先方法创建了一个Jax-WS WebService。创建WSDL和XSD,然后使用wsimport工具生成其余工件,为SEI提供实现。将WebService应用程序部署到Eclipse Helios中的GlassFish(Glassfish适配器和Eclipse中安装的插件)。…