选择具有给定子值的XML节点并更新不同的子元素

时间:2017-11-28 18:41:00

标签: c# xml c#-4.0

我有以下xml文件:

<LabelImageCreator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <PrintFieldList>
    <PrintFieldDefinition>
      <FieldName>Facility</FieldName>
      <DataParameterName>Address</DataParameterName>
      <FieldFont>
        <FontName>Arial</FontName>
        <FontSize>10</FontSize>
        <FontStyle>Regular</FontStyle>
      </FieldFont>
      <CurrentDataValue/>
    </PrintFieldDefinition>
    <PrintFieldDefinition>
      <FieldName>Country</FieldName>
      <DataParameterName>CountryofOrigin</DataParameterName>
      <WrapField>false</WrapField>
      <FieldFont>
        <FontName>Arial</FontName>
        <FontSize>8</FontSize>
        <FontStyle>Regular</FontStyle>
      </FieldFont>
      <CurrentDataValue/>
      <TextPrefix>Produce of </TextPrefix>
    </PrintFieldDefinition>
  <PrintFieldList>
<LabelImageCreator>

我必须选择字段名称为Facility的属性,并将地址(例如:No 2546,Gorrge street,California,US)添加到<CurrentDataValue/>字段并保存。

我尝试使用以下代码,

 XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(path);
  var node = xmlDocument.DocumentElement.SelectSingleNode(
             "./PrintFieldList/PrintFieldDefinition[@FieldName='Facility']");

上面的代码虽然在调试它时不起作用。任何人都可以指导我如何选择和更新xml属性。

2 个答案:

答案 0 :(得分:1)

一些小问题:

  • 您需要从根元素LabelImageCreator
  • 开始
  • FieldName是一个元素,而不是一个属性,因此FieldName而不是@FieldName
  • Xml文档上的结束标记不匹配。

如果您要选择父CurrentDataValue的子元素PrintFieldDefinition,其子FieldName的值为Facility

var node = xmlDocument.DocumentElement.SelectSingleNode(
"/LabelImageCreator/PrintFieldList/PrintFieldDefinition[FieldName='Facility']/CurrentDataValue");

然后更改值:

node.InnerText = "No 2546, Gorrge street, California, US";      

答案 1 :(得分:1)

我会使用 XDocument 而不是 XmlDocument (它允许你使用linq,在我看来,这比使用xpath更容易)。

您可以找到这样的节点,我相信您也可以更新它们(首先搜索并获取值,然后再次搜索并在另一个节点上更新)。

示例:

public class Music : MonoBehaviour 
{
    public AudioClip[] clips;
    private AudioSource audiosource;
    public bool randomPlay = false;
    private int currentClipIndex = 0;

    void Start()
    {
        audiosource = FindObjectOfType<AudioSource>();
        audiosource.loop = false;
    }

    void Update()
    {
        if(!audiosource.isPlaying)
        {
            AudioClip nextClip;
            if (randomPlay)
            {
                nextClip = GetRandomClip();
            }
            else
            {
                nextClip = GetNextClip();
            }
            currentClipIndex = clips.IndexOf(nextClip);
            audiosource.clip = nextClip;
            audiosource.Play();
        }
    }

    private AudioClip GetRandomClip()
    {
        return clips[Random.Range(0, clips.Length)];
    }

    private AudioClip GetNextClip()
    {
        return clips[(currentClipIndex + 1) % clips.Length)];
    }

    private void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }
}
相关问题