对于一个项目,我创建了一个可与TIA Portal V14,PLC/siemens环境连接的开放式API的应用程序。C#查找并替换部分XML innertextxt
对于这个应用程序,我基本上是从零开始构建一个XML文件。 为了达到这个目的,我创建了自己的XML库文件,其中包含了使用System.XML的XML块,我可以将其复制到模板中以最终创建一个XML文件,该文件可以使用Tia Portal中的对象生成一个屏幕。
我遇到的问题是我似乎无法找到或想到一种方法来查找和替换一个片一个元素innertext。
<VEG_Connection_Config>
<!-- Static Properties hold objects with properties that are always the same -->
<StaticProperties>
<!-- List of static objects -->
<GlobalLibraryObjects>
<!-- valve -->
<GlobalLibraryObject type="200" events="" properties="">
<Hmi.Screen.SymbolLibrary ID="2" CompositionName="ScreenItems">
<!-- valve -->
<AttributeList>
<AboveUpperLimitColor>255, 0, 0</AboveUpperLimitColor>
<BackColor>192, 192, 192</BackColor>
<BackFillStyle>Transparent</BackFillStyle>
<BelowLowerLimitColor>255, 255, 0</BelowLowerLimitColor>
<BlinkColor>0, 0, 255</BlinkColor>
<Enabled>true</Enabled>
<FillColorMode>Original</FillColorMode>
<FixedAspectRatio>false</FixedAspectRatio>
<Flashing>None</Flashing>
<FlashingOnLimitViolation>false</FlashingOnLimitViolation>
<Flip>None</Flip>
<ForeColor>0, 0, 0</ForeColor>
<Height>46</Height>
<Left>10</Left>
<ObjectName>DB_Stat_obj.$TAGNAME</ObjectName>
这是我的XML库的一小部分。在底部,您可以看到一个名为ObjectName的元素,它包含了无缝文本DB_Stat_obj。$ TAGNAME
$ TAGNAME是我想要由读取CSV文件的标记名替换的部分。 所以最终的结果应该是DB_Stat_obj.1000P01。
现在是我的问题,如果有人知道如何使用System.XML找到$ TAGNAME并将其替换为其他东西。
据我所知,使用System.Xml.Linq的我可以通过解析文件,并使用此代码只替换位:
string keyword = "$TAGNAME";
var doc = XDocument.Load(screenLocation);
List<XElement> query = doc.Descendants().
Where(x => !x.HasElements &&
x.Value.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList();
query.ForEach(n => n.Value = n.Value.Replace(keyword, objectName));
doc.Save(screenLocation);
但考虑到我的整个应用程序已经与了System.XML做出/ XmlDocument我无法使用此代码。 我已经尝试将XmlDocument转换为XDocument只是为了替换$ TAGNAME并将其转换回来,但那也没有奏效。 转换代码下面
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
我希望有另外一个awnser这个可以点我在正确的方向。
TL; DR;如何找到找到并使用的System.Xml
感谢替换的innerText的一部分,
//吉荣
您不需要。为InnerText使用“字符串”,然后对该字符串进行操作。 –